package com.infoteria.asteria.flowlibrary2.component.system;

import com.infoteria.asteria.flowengine2.execute.ExecuteContext;
import com.infoteria.asteria.flowengine2.flow.InputConnector;
import com.infoteria.asteria.flowlibrary2.FlowException;
import com.infoteria.asteria.flowlibrary2.component.SimpleComponent;
import com.infoteria.asteria.flowlibrary2.stream.StreamDataObject;
import com.infoteria.asteria.flowlibrary2.stream.StreamType;
import com.infoteria.asteria.flowlibrary2.property.Property;
import com.infoteria.asteria.flowlibrary2.property.StringProperty;
import com.infoteria.asteria.flowlibrary2.property.EnumProperty;

/**
 * ログを出力するコンポーネント
 */
public class LogComponent extends SimpleComponent {
	
	public static final String COMPONENT_NAME = "Log";
	public String getComponentName() { return COMPONENT_NAME;}
	
	private static final int LOGLEVEL_FATAL     = 0;
	private static final int LOGLEVEL_ERROR     = 1;
	private static final int LOGLEVEL_WARN      = 2;
	private static final int LOGLEVEL_INFO      = 3;
	private static final int LOGLEVEL_DEBUGINFO = 4;
	private static final int LOGLEVEL_DEBUG     = 5;
	
	private StringProperty _message = new StringProperty("Message");
	private EnumProperty _loglevel = new EnumProperty("LogLevel", true, true, "info");
	
	public LogComponent() {
		getInputConnector().setAcceptLinkCount(1);
		getInputConnector().setAcceptType(StreamType.ALL);
		getOutputConnector().setAcceptType(StreamType.ALL);
		
		_loglevel.addEnumeration("fatal");
		_loglevel.addEnumeration("error");
		_loglevel.addEnumeration("warn");
		_loglevel.addEnumeration("info");
		_loglevel.addEnumeration("debugInfo");
		_loglevel.addEnumeration("debug");
		
		registProperty(_message);
		registProperty(_loglevel);
	}
	
	public boolean execute(ExecuteContext context) throws FlowException {
		StreamDataObject input = getInputConnector().getStream();
		
		String msg = null;
		if (_message.isNull())
			msg = getName();
		else
			msg = _message.strValue();
		
		switch (_loglevel.getIndex()) {
			case LOGLEVEL_FATAL:
				context.fatal(msg);
				break;
			case LOGLEVEL_ERROR:
				context.error(msg);
				break;
			case LOGLEVEL_WARN:
				context.warn(msg);
				break;
			case LOGLEVEL_INFO:
				context.info(msg);
				break;
			case LOGLEVEL_DEBUGINFO:
				context.debugInfo(msg);
				break;
			case LOGLEVEL_DEBUG:
				context.debug(msg);
				break;
			default:
				throw new IllegalStateException();
		}
		passStream();
		return true;
	}
	
}
