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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Iterator;

import jp.hasc.hasctool.core.data.EnumCommand;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.runtime.filter.AbstractFilter;
import jp.hasc.hasctool.core.util.CoreUtil;

/**
 * メタ要素(metaElement)のリストをカンマ","区切りで出力します
 * @author hiro
 */
public class MetaElementListCreator extends AbstractFilter{

	private HashSet<String> hset_ = new HashSet<String>();


	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String filePath =(String)message;
			try{
				InputStream inps = getRuntimeContext().getFileStreamProvider().openInputStream(filePath);
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inps, RuntimeContext.DEFAULT_CHARSET));
				while(true){
					String line = bufferedReader.readLine();
					if (line == null) {
						break;
					} else {
						String[] row = line.split(":");
						String key = row[0];
						key = key.trim();
						if(!(hset_.contains(key))){
							hset_.add(key);
							System.out.println(key);
						}					
					}
				}
				bufferedReader.close();
				inps.close();
			} catch (IOException ex) {
				CoreUtil.throwAsRuntimeException(ex);
			} catch (RuntimeException ex) {
			}
		} else if (message == EnumCommand.END) {
			Iterator<String> it = hset_.iterator();
			String row = "Element: ";
			while (it.hasNext()) {
				String key = (String) it.next();
				row += "," + key;
			}
			outputMessage(row);
			outputMessage(EnumCommand.END);
		}else{
			//BEGIN message
			outputMessage(message);
		}
	}

}
