/*
 * Created on Jul 16, 2008 (C) Copyright TANDBERG Television Ltd.
 */

package com.tandbergtv.watchpoint.pmm.action.schedule.distribution;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

import org.apache.log4j.Logger;

/**
 * Transformer that ensures the result file has the same contents as the input file.
 * 
 * @author Vijay Silva
 */
public class IdentityScheduleTransformer implements IScheduleTransformer {

	/* The logger */
	private static final Logger logger = Logger.getLogger(IdentityScheduleTransformer.class);

	/**
	 * Transformer that simply copies the contents of the source file to the result file
	 * 
	 * @see com.tandbergtv.watchpoint.pmm.action.schedule.distribution.IScheduleTransformer#transform(java.io.File,
	 *      java.io.File)
	 */
	public void transform(File sourceFile, File resultFile) throws ScheduleTransformException {
		String sourceName = sourceFile.getAbsolutePath();
		String resultName = resultFile.getAbsolutePath();

		FileChannel inputChannel = null;
		FileChannel outputChannel = null;
		try {
			inputChannel = new FileInputStream(sourceFile).getChannel();
			outputChannel = new FileOutputStream(resultFile).getChannel();

			long maxCount = 1024 * 1024;
			long inputChannelSize = inputChannel.size();
			long position = 0;
			while (position < inputChannelSize) {
				position += inputChannel.transferTo(position, maxCount, outputChannel);
			}
		} catch (Exception e) {
			throw new ScheduleTransformException("Failed to copy file: " + sourceName
					+ " to file: " + resultName + ", error: " + e.getMessage(), e);
		} finally {
			this.close(inputChannel, sourceName);
			this.close(outputChannel, resultName);
		}
	}

	/* Closes a stream, logging any problems in the process */
	private void close(Closeable closeable, String name) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (Exception e) {
				logger.warn("Failure when closing: " + name, e);
			}
		}
	}
}
