package jp.hasc.hasctool.core.runtime.filter.file;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.runtime.sink.LineWriterSink;
import jp.hasc.hasctool.core.runtime.source.LineReaderSource;

/**
 * 旧版のCSVファイル（timeが最終フィールド）を、新版のCSVファイル（timeが最初のフィールド）に変換します。
 * 使い方：java -cp [classディレクトリへのパス] jp.hasc.hasctool.core.runtime.filter.file.UpdateCSVFileTool [filenames]
 * @author iwasaki
 */
public class UpdateCSVFileTool {
	public static void main(String[] args) throws Exception {
		UpdateCSVFileTool tool=new UpdateCSVFileTool();
		ArrayList<String> filenames=new ArrayList<String>();
		for(int i=0;i<args.length;++i) {
			filenames.add(args[i]);
		}
		for(String filename:filenames) {
			tool.processFile(filename);
		}
		System.exit(0);
	}

	public void processFile(String filename) throws Exception {
		File file=new File(filename);
		File workfile=new File(filename+".$temp");
		File backupfile=new File(filename+".old");
		
		System.out.println("converting "+filename);
		
		if (backupfile.isFile()) {
			System.out.println("Error: "+backupfile+" already exists.");
			return;
		}
		
		RuntimeContext ctx=new RuntimeContext();
		
		LineReaderSource lr=new LineReaderSource();
		lr.setReader(new FileReader(file));
		lr.setup(ctx);
		
		CSVToVectorFilter csvr=new CSVToVectorFilter();
		csvr.setTimeColumnIndex(-1);
		csvr.setup(ctx);
		
		VectorToCSVFilter csvw = new VectorToCSVFilter();
		csvw.setup(ctx);
		
		LineWriterSink lw=new LineWriterSink();
		lw.setWriter(new FileWriter(workfile));
		lw.setup(ctx);
		
		//
		lr.getOutputPort().connect(csvr.getInputPort());
		csvr.getOutputPort().connect(csvw.getInputPort());
		csvw.getOutputPort().connect(lw.getInputPort());
		
		//
		ctx.startTasks();
		ctx.awaitTasksTermination();
		System.out.println("done.");
		//
		if (!file.renameTo(backupfile)) throw new IOException("can't rename to "+backupfile);
		if (!workfile.renameTo(file)) throw new IOException("can't rename to "+file);
	}

}
