package com.eactive.eai.adapter.websocket;

import java.nio.charset.Charset;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;

import com.eactive.eai.adapter.AdapterGroupVO;
import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.adapter.ElinkDefaultAdapter;
import com.eactive.eai.common.message.MessageType;
import com.eactive.eai.common.util.Logger;

public class WebSocketAdapterFacade extends ElinkDefaultAdapter {
	static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);

	private static WebSocketAdapterFacade instance = new WebSocketAdapterFacade();

	public static final String ADAPTER_GORUP_NAME = "ADAPTER_GROUP_NAME";

	public static WebSocketAdapterFacade getInstance() {
		return instance;
	}

	public Object execute(Properties prop, Object message, Properties tempProp) throws Exception {
		String adapterGroupName = tempProp.getProperty(ADAPTER_GORUP_NAME);
		if (logger.isDebug())
			logger.debug("[WebSocketAdapterFacade] | Outbound Adapter Group is " + adapterGroupName);

		byte[] request = null;
		if (message instanceof byte[]) {
			request = (byte[]) message;
		} else {
			throw new Exception(adapterGroupName + " | [WebSocketAdapterFacade] cannot send object type : "
					+ message.getClass().getName());
		}

		AdapterManager manager = AdapterManager.getInstance();
		AdapterGroupVO agv = manager.getAdapterGroupVO(adapterGroupName);
		String encode = StringUtils.defaultIfBlank(agv.getMessageEncode(), Charset.defaultCharset().name());
//         String encode = "utf-8";
//         if (MessageType.UJSON.equals(agv.getMessageType()) || MessageType.JSON.equals(agv.getMessageType())){
		if (MessageType.JSON.equals(agv.getMessageType())) {

//        	 if (MessageType.JSON.equals(agv.getMessageType())) {
//        		 encode = "ms949";
//        	 }

//         	String id = ExtMessageConverter.getTellerId(message, agv.getMessageType());
			// BID와 책임자승인 거래에 따라 추출해야 할 위치가 다르고
			// Group BID일 경우까지 고려하여 Outboud에서 추출하여 설정하도록 함 (2021-03-26)
			String receiverId = tempProp.getProperty("RECEIVER_ID");

			if (receiverId == null) {
				logger.warn("[WebSocketAdapterFacade] | RECEIVER_ID is NULL " + new String(request, encode));
				return null;
			}
			WebSocket webSocket = WebSocketSessionManager.getInstance().getSession(adapterGroupName, receiverId);
			if (logger.isDebug()) {
				logger.debug("[WebSocketAdapterFacade] | receiverId=" + receiverId);
				logger.debug("[WebSocketAdapterFacade] | adapterGroupName=" + adapterGroupName);
				logger.debug("[WebSocketAdapterFacade] | websocket=" + webSocket.getRemoteSocketAddress());
				logger.debug("[WebSocketAdapterFacade] | request=" + new String(request, encode));
			}

			if (webSocket == null) {
				logger.warn("[WebSocketAdapterFacade] | WebSocket Session is NULL receiverId" + receiverId);
				return null;
			} else {
				webSocket.send(new String(request, encode));
			}
		}
		return null;
	}
}
