package com.eactive.eai.transformer.message;

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

import org.apache.commons.lang3.StringUtils;

import com.eactive.eai.common.EAITable;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.transformer.layout.LayoutTypeKey;

public class ISO8583MessageFactory {
	static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	public static Map<String, String> ISO8583_LAYOUT_TYPE_CLASS_MAP = new HashMap<>();
	public static Map<String, String> ISO8583_MESSAGE_TYPE_CLASS_MAP = new HashMap<>();

	/**
	 * @formatter:off
	 * Custom ISO8583 메시지 추가시
	 * - ONLWeb: Custom Mesaage java 추가, 아래 맵에 추가(CustomizingAppInitializer.java에서 추가)
	 * - EMSWeb: Custom Mesaage java 추가, 아래 맵에 추가(로그조회시 parsing 위해)
	 * @formatter:on
	 */
	static {
		ISO8583_MESSAGE_TYPE_CLASS_MAP.put(EAITable.ISO8583_TYPE, "com.eactive.eai.transformer.message.ISO8583Message");
		ISO8583_LAYOUT_TYPE_CLASS_MAP.put(LayoutTypeKey.ISO8583, "com.eactive.eai.transformer.message.ISO8583Message");
		logger.info("ISO8583MessageFactory registered - {}={}", EAITable.ISO8583_TYPE,
				"com.eactive.eai.transformer.message.ISO8583Message");
		logger.info("ISO8583MessageFactory registered - {}={}", LayoutTypeKey.ISO8583,
				"com.eactive.eai.transformer.message.ISO8583Message");
	}

	public static ISO8583Message create(String key) {
		String className = ISO8583_MESSAGE_TYPE_CLASS_MAP.get(key);

		if (StringUtils.isBlank(className)) {
			className = ISO8583_LAYOUT_TYPE_CLASS_MAP.get(key);
		}

		if (StringUtils.isBlank(className)) {
			logger.error("ISO8583_MESSAGE_TYPE_CLASS_MAP(ISO8583_LAYOUT_TYPE_CLASS_MAP) Not set. - {}", key);
			return null;
		}

		return ISO8583MessageFactory.createByClassName(className);
	}

	@SuppressWarnings("rawtypes")
	public static ISO8583Message createByClassName(String className) {
		ISO8583Message message = null;
		try {
			Class cl = Class.forName(className);
			message = (ISO8583Message) cl.newInstance();
		} catch (Exception e) {
			logger.error("Cannot create a ISO8583Message. - {}", className);
		}

		return message;
	}

	public static boolean isISO8583Message(String messageType) {
		return ISO8583_MESSAGE_TYPE_CLASS_MAP.containsKey(messageType);
	}

	public static boolean isISO8583Layout(String layoutType) {
		return ISO8583_LAYOUT_TYPE_CLASS_MAP.containsKey(layoutType);
	}
}