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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.util.CoreUtil;

/**
 * メタ要素(metaElement)の内容を出力します
 * @author hiro
 */

public class MetaElementFilter extends AbstractElementFilter{

	String element_;
	String[] metaElement_;

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		super.element_ = this.element_;
		metaElement_ = element_.split(",");
	}

	String getFeature(String filePath){
		HashMap<String, String> hmap = new HashMap<String, String>();
		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();
					String val = row[row.length-1];
					val = val.trim();
					if(!(key.equals(val)))hmap.put(key, val);
				}
			}
			bufferedReader.close();
			inps.close();
		} catch (IOException ex) {
			CoreUtil.throwAsRuntimeException(ex);
		} catch (RuntimeException ex) {
		}
		String row = "";
		for(int i=0; i<metaElement_.length; i++){
			if(i != 0)row += ",";
			if(hmap.get(metaElement_[i]) == null){
				row += "null";
			}else{
				row += hmap.get(metaElement_[i]);
			}
		}

		return row;
	}

	public void setMetaElement(String metaEle) {
		element_ = metaEle;
	}
}
