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

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

/**
 * メッセージを指定した文字で分割するフィルタです
 * @author hiro
 */
public class MessageSplitter extends AbstractFilter{

	private String delimiter_;
	private String index_;
	private int[] indexList_;

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

	private void run(){
		String[] iList;
		if (0 <= index_.indexOf(",")){
			iList = index_.split(",");
		} else {
			iList = new String[1];
			iList[0] = index_;
		}
		int ilen = iList.length;
		indexList_ = new int[ilen];
		for(int i=0; i<ilen; i++){
			indexList_[i] = Integer.parseInt(iList[i]);
		}
	}

	@Override
	public void processMessage(Object message) throws InterruptedException {
		if (message instanceof String) {
			String s =(String)message;
			String[] part = s.split(delimiter_);
			String newValue = part[indexList_[0]];
			for(int i=1; i<indexList_.length; i++){
				newValue += delimiter_ + part[indexList_[i]];
			}
			outputMessage(newValue);
		}else{
			//BEGIN,END message
			outputMessage(message);
		}
	}


	public void setIndex(String index){
		index_ = index;
	}

	public void setDelimiter(String delimiter){
		delimiter_ = delimiter;
	}
}
