package com.eactive.eai.outbound;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import org.apache.commons.lang.StringUtils;

import com.eactive.eai.common.message.EAIMessage;
import com.eactive.eai.common.message.EAIMessageKeys;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.Keys;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.LogKeys;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.control.LogSender;

public class MessageLoggingProcess extends DefaultProcess {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public int logSequence;
//	public EAIMessage resEaiMsg;
//	public EAIMessage reqEaiMsg;
//	public java.util.Properties callProp;
//	static final long serialVersionUID = 1L;

	public static final String LOG_DIR = "MsgReceiveDir";

	@Override
	public void flow() throws Exception {
		// WarmUp start
		if (!isRealCall()) {
			return;
		}
		// WarmUp end

		// LogToFile
		logToFile();
		// Condition
		if (isAsyncAsyncIF()) {
			// SendEAILog
			logSenderSend();
		}
	}

	public EAIMessage clientReturn() {
		return this.reqEaiMsg;
	}

	public void logSenderSend() throws Exception {
		LogSender.send(this.logSequence, this.reqEaiMsg, this.callProp);
	}

	public boolean isAsyncAsyncIF() {

		String svcTsmtUsgTP = reqEaiMsg.getSvcTsmtUsgTp();
		String psvItfTp = reqEaiMsg.getCurrentSvcMsg().getPsvItfTp();

		if (EAIMessageKeys.ASYNC_SVC.equals(svcTsmtUsgTP) && EAIMessageKeys.ASYNC_SVC.equals(psvItfTp)) {
			return true;
		} else {
			return false;
		}
	}

	public void logToFile() throws Exception {
		Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
		if (logger.isDebug())
			logger.debug("MessageLoggingProcess] executing logToFile method. ********************");
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			String sLogDirectory = PropManager.getInstance().getProperty(LogKeys.LOGGER_INFO, LogKeys.LOG_DIRECOTRY_PREFIX);
        	String rootPath = null;
        	boolean pathExist = true;
			
        	if(StringUtils.isEmpty(sLogDirectory)) {
        		sLogDirectory = ".";
        	}
        	rootPath = sLogDirectory + File.separator + System.getProperty(Keys.SERVER_KEY) + File.separator + LOG_DIR;
			File dir = new File(rootPath);
			if (!dir.exists()) {
				pathExist = dir.mkdir();
			}
			if(!pathExist) {
				logger.warn("log directory create failed skip file logging - " + rootPath);
				return;
			}
			
			String logFileName = DatetimeUtil.getCurrentTimeMillis() + "-" + this.reqEaiMsg.getSvcOgNo() + ".log";
			
			File f = new File(dir, logFileName);
			fw = new FileWriter(f);
			bw = new BufferedWriter(fw);
			
			String charset = this.callProp.getProperty(com.eactive.eai.adapter.Keys.CHARSET_KEY_IN, "MS949");
			Object data = this.reqEaiMsg.getStandardMessage().getBizData();
			if (data == null) {
				bw.write("BizMsg is null.");
			} else if (data instanceof byte[]) {
				byte[] buff = (byte[]) data;
				bw.write(new String(buff, charset));
			} else if (data instanceof String) {
				bw.write((String)data);
			} else {
				bw.write(data.toString());
			}
			bw.flush();
		} catch (Exception e) {
			logger.error("logToFile error", e);
			throw e;
		} finally {
			this.logSequence = 400;
			this.resEaiMsg = this.reqEaiMsg;
			try {
				if (bw != null)
					bw.close();
			} catch (Exception e) {
			}
			try {
				if (fw != null)
					fw.close();
			} catch (Exception e) {
			}
		}
	}

	@Override
	public void logSenderCtrlSendReq() throws Exception {
		

	}

	@Override
	public void logSenderCtrlSendRes() throws Exception {
		

	}

	@Override
	public void outboundCtrlCallService() throws Exception {
		

	}

	@Override
	public void outboundCtrlCallServiceAsync() throws Exception {
		

	}

	@Override
	public void transControlTransformSingleRes() throws Exception {
		

	}

	@Override
	public void transControlTransformSingleReq() throws Exception {
		

	}

	@Override
	public void printCallError(Exception e1) throws Exception {
		

	}

	@Override
	public void setRcvLogInfo() throws Exception {
		

	}

	@Override
	public void setTopicResult() throws Exception {
		

	}

	@Override
	public void checkResultMessage() throws Exception {
		

	}

	@Override
	public void checkSendResult() throws Exception {
		

	}

	@Override
	public void init() throws Exception {
		

	}

	@Override
	public void setSendMsg() throws Exception {
		

	}

	@Override
	public void getTopicProperty() throws Exception {
		

	}

	@Override
	public void performSend() throws Exception {
		

	}

	@Override
	public void performRecv() throws Exception {
		

	}

	@Override
	public void storeMessage() throws Exception {
		

	}

	@Override
	public void getBizMessage() throws Exception {
		

	}

	@Override
	public void waitCheckForSync() throws Exception {
		

	}

	@Override
	public void transControlHeaderTrnsformSinglesRes() throws Exception {
		

	}

}
