package com.eactive.eai.common.util;

import com.eactive.eai.common.errorcode.ErrorCodeManager;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.server.EAIServerManager;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/** 
 * 1. 기능 : SMS Message Filtering, Logging Util
 * 2. 처리 개요 : SMS 대상 메시지를 Filtering하여 File Write(kbsms.log) 한다.
 *      - 동일 Message 일정시간 skip
 *      - 동일 Message count
 *      - SMS Message layout 정의
 *      - reset SMS Message Collections
 */
public class SMSLogUtil extends QuartzJobBean {

	private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	private static Logger loggerSMS = Logger.getLogger(Logger.LOGGER_SMS);

	public static Map<String, SMSLogVO> m = Collections.synchronizedMap(new HashMap<String, SMSLogVO>());

//	 SMS 발송 주기
	private static long smsInteval = Long
			.parseLong(PropManager.getInstance().getProperty(LogKeys.LOGGER_SMS_PREFIX, LogKeys.SMS_INTERVAL));

	/**
	 * management SMS log message - make message layout - check, update log message
	 * Map
	 * 
	 * @param svcName
	 * @param logMsg  sms log data format 월일 시간[건수]인스턴스 메시지 1103
	 *                13:56:58.715[1]mcc11 HTTP호출에러|MUTMIAS00000170S1
	 */
	public static void loggingSMS(String svcName, String logMsg) {
		String nodeName = EAIServerManager.getInstance().getGroupInstId();
		String logMessage = nodeName + " " + logMsg + "|" + svcName;
		SMSLogVO vo = m.get(logMessage);
		if (vo == null) {
			m.put(logMessage, new SMSLogVO(System.currentTimeMillis(), 1, logMessage));
			logMessage = "[1]" + logMessage;
			writeSMSMessage(logMessage);
		} else {
			vo.increaseOccurCount();
			if ((System.currentTimeMillis() - vo.getInitTimeMillis()) > (smsInteval * 1000 * 60)) {
				vo.setInitTimeMillis(System.currentTimeMillis()); // reflesh init Time
				logMessage = "[" + vo.getOccurCount() + "]" + logMessage;
				writeSMSMessage(logMessage);
			}
		}
	}

	public static void loggingSMSWithCode(String svcName, String code) {
		String error = ErrorCodeManager.getInstance().getMessageEtc(code);
		if (code == null)
			code = "UNDEFINE";
		loggingSMS(svcName, StringUtil.chunkString(error, 16));
	}

//	 management SMS log message for SocketAdapter
	public static void loggingSMS4Soc(String adptName, String adptDesc, String code) {
		String svcName = StringUtil.chunkString(adptDesc, 10) + "|" + adptName;
		loggingSMSWithCode(svcName, code);
	}

//	write SMS log use SMS Logger
	private static void writeSMSMessage(String logMessage) {
		try {
			loggerSMS.error(logMessage);
		} catch (Exception e) {
			logger.error("SMS logging error", e);
		}
	}

//	 Scheduled SMS Log Info Map clear, call by spring config
	protected void executeInternal(JobExecutionContext ctx) throws JobExecutionException {
		m.clear();
		logger.info("purge SMSLogVO Map!");
	}
}
