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

import weka.classifiers.Classifier;
import weka.core.Instance;
import weka.core.Instances;
import jp.hasc.hasctool.core.runtime.RuntimeContext;
import jp.hasc.hasctool.core.runtime.filter.AbstractFilter;

/**
 * weka ライブラリを利用して識別を行うフィルタです
 * @author hiro
 */

public class EvaluationFilter extends AbstractFilter {

	//識別対象を指定
	String element_;
	String[] eList_;
	
	//特徴量を指定
	String feature_;
	String[] fList_;
	int fLength_;

	WekaDataInstance wdi_;
	Instances learningDataset_;
	Classifier predictiveModel_;
	String predictElement_;

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		eList_ = element_.split(",");
		fList_ = feature_.split(",");
		fLength_ = fList_.length;
	}
	
	public void setElement(String element) {
		element_ = element;
	}

	public void setFeature(String feature) {
		feature_ = feature;
	}

	//インスタンス作成メソッド
	protected Instance createInstance(Instances associatedDataSet, String[] data) {
		Instance instance = new Instance(fLength_+1);
		instance.setDataset(associatedDataSet);
		for(int i=0; i<fLength_; i++){
			instance.setValue(i, Double.parseDouble(data[i]));
		}
		instance.setValue(fLength_, eList_[0]);
		return instance;
	}

	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof WekaDataInstance) {
			wdi_ = (WekaDataInstance)message;
			learningDataset_ = wdi_.getLearningDataset();
			predictiveModel_ = wdi_.getPredictiveModel();

		} else if (message instanceof String) {
			try {
				String s = (String)message;
				String[] data = s.split(",");
				int len = data.length;
				String filePath = data[0];
				String[] val = new String[len-1];
				for(int i = 0; i<len-2; i++){
					val[i] = data[i+2];
				}
				val[len-2] = eList_[0];
				Instance perdictInstance = createInstance(learningDataset_, val);
				double prediction = predictiveModel_.classifyInstance(perdictInstance);
				predictElement_ = perdictInstance.classAttribute().value((int) prediction); 
				outputMessage(filePath + "," + predictElement_);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
				} else {
			// その他のメッセージはそのまま出力(BEGIN,ENDを含む)
			outputMessage(message);
		}
	}
}
