package com.eactive.eai.adapter.app.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;

import com.eactive.eai.adapter.app.BusinessApplication;
import com.eactive.eai.common.util.DatetimeUtil;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.common.util.StringUtil;

public class OnlineToFileWriter implements BusinessApplication {
	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public static final String CLASS_PROPS = "BUSINESS_CLASS_PROPS";
	public static final String CLASS_PROPS_BASE_FILE_PATH = "baseFilePath";
	public static final String CLASS_PROPS_ENCODE = "encode";
	public static final String CLASS_PROPS_FILE_PATH_EXT = "fileExt";

	/**
	 * @formatter:off
	 * Adapter property ¼³Á¤: BUSINESS_CLASS_PROPS
	 *  - ex) baseFilePath=/data/onlineToJson, fileExt=json
	 * @formatter:on
	 */
	@Override
	public Object executeApplication(Properties prop, Object message, Properties tempProp) throws Exception {
		String classPropsStr = prop.getProperty(CLASS_PROPS);
		Properties classProp = StringUtil.getProperties(classPropsStr);
		String baseFilePath = classProp.getProperty(CLASS_PROPS_BASE_FILE_PATH);
		if (StringUtils.isBlank(baseFilePath)) {
			throw new Exception(String.format("Property(%s) is not setted", CLASS_PROPS_BASE_FILE_PATH));
		}

		String encode = classProp.getProperty(CLASS_PROPS_ENCODE, "UTF-8");
		String fileExt = classProp.getProperty(CLASS_PROPS_FILE_PATH_EXT, "txt");
		String eaiSvcName = tempProp.getProperty(BusinessApplication.EAI_SVC_NAME);
		if (StringUtils.isBlank(eaiSvcName)) {
			throw new Exception("Can not find serviceId");
		}
		String dirStr = StringUtils.removeEnd(baseFilePath, "/") + "/" + eaiSvcName;
		File dir = new File(dirStr);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		String fileName = DatetimeUtil.getFormattedDate("yyyyMMdd-HHmmssSSS") + "." + fileExt;
		File file = new File(dir, fileName);
		
		Map<String, String> resultMap = new HashMap<>();
		
		try (
			FileWriter  fw = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(fw);
		){
			if (message == null) {
				logger.warn("message is null");
			} else if (message instanceof byte[]) {
				byte[] buff = (byte[]) message;
				bw.write(new String(buff, encode));
			} else {
				bw.write(message.toString());
			}
			bw.flush();

			resultMap.put("RESULTCD", "000");
			resultMap.put("RESULTMSG", "Success");
			resultMap.put("FILENAME", fileName);
		} catch (Exception e) {
			logger.error("OnlineToFileWriter error", e);
			throw e;
		}

		JSONObject resultJsonObject = new JSONObject();
		resultJsonObject.putAll(resultMap);
		return resultJsonObject.toJSONString().getBytes();
	}
}
