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

import jp.hasc.hasctool.core.runtime.filter.AbstractFilter;
import jp.hasc.hasctool.core.runtime.RuntimeContext;

/**
 * label情報の編集を行います
 * @author hiro
 */

public class LabelEditor extends AbstractFilter{

	String labelInf_;
	String[] labelArray_;
	boolean single_ = false;

	@Override
	public void setup(RuntimeContext context) {
		super.setup(context);
		start();
	}

	private void start(){
		if(labelInf_.contains(",")){
			labelArray_ = labelInf_.split(",");
		}else{
			single_ = true;
		}
	}

	private String editLabel(String val){
		String label = null;
		if(single_){
			if (0 <= val.indexOf(labelInf_)){
				label = labelInf_;
			}
		}else{
			for(int i=0; i<labelArray_.length; i++){
				if (0 <= val.indexOf(labelArray_[i])){
					label = labelArray_[i];
					break;
				}
			}
		}
		return label;
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String line =(String)message;
			String[] row = line.split(",");
			if(row.length == 3){
				String label = editLabel(row[2]);
				if(label != null){
					outputMessage(row[0] + "," + row[1] + "," + label);
				}
			}else{
				outputMessage(message);
			}
		} else {
			//BEGIN message
			outputMessage(message);
		}
	}

	public void setLabelInf(String labelInf){
		labelInf_ = labelInf;
	}
}
