package com.eactive.eai.adapter.jtc;

import com.eactive.eai.adapter.ElinkDefaultAdapter;
import com.eactive.eai.adapter.socket2.common.SMSLogger;
import com.eactive.eai.common.util.CommonLib;
import com.eactive.eai.common.util.Logger;
import tmax.jtc.TuxService;
import tmax.jtc.io.TuxBuffer;
import tmax.jtc.io.TuxCallDescripter;
import tmax.jtc.io.TuxFieldBuffer;

import java.util.Properties;

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

    public static final String ADAPTER_GORUP_NAME="ADAPTER_GROUP_NAME";
    
    public static final String DOMAIN_NAME      = "domain.name";
    public static final String SERVICE_NAME   = "service.name";
    public static final String BUFFER_TYPE  = "buffer.type"; // CARRAY | STRING | FML | FML32
    public static final String DEFAULT_BUFFER_TYPE  = "CARRAY";
    public static final String RESPONSE_TYPE  = "response.type";
     
    
    /** 
    * 1. 기능 :  HttpClientAdapter default 생성자
    * 2. 처리 개요 : 
    *     - property 정보를 가져와 MultiThreadedHttpConnectionManager 속성 설정
    *     - HttpClient의 instance 생성
    * 3. 주의사항 
    *
    **/
    public JtcClientAdapter() {
        super();
    }
    
    /** 
    * 1. 기능 :  전문과 같은 Raw Data 통신에 사용
    * 2. 처리 개요 : 
    *     - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다.
    * 3. 주의사항 
    *
    * @param    prop   WebT Adapter properties 속성 정보
    * @param    message 송신 전문
    * @return   반환 된 byte[] Object
    * @exception    Exception 수동 시스템 간 통신 중 발생
    **/
    // -Dwebt.properties=
    public Object execute(Properties prop, Object message) throws Exception
    {
//    	String adapterGroupName = prop.getProperty(ADAPTER_GORUP_NAME);
//    	String adapterName      = prop.getProperty("adapterName");
    	
    	byte[] data = null;
        if(message instanceof byte[]) {
            data = (byte[])message;
        } else if( message instanceof String) {
            data = ((String)message).getBytes();
        } else {
            throw new Exception("RECEAIAHA011");
        }
        
        String domainName     = prop.getProperty(DOMAIN_NAME,"TDOM");
        String serviceName     = prop.getProperty(SERVICE_NAME,"SEAIRECV");
        String bufferType    = prop.getProperty(BUFFER_TYPE, DEFAULT_BUFFER_TYPE);
        String responseType    = prop.getProperty(RESPONSE_TYPE,"SYNC");

        try{

        	TuxService service = new TuxService(domainName, serviceName);

        	if (logger.isDebug()){
	        	logger.debug("JtcClientAdapter] ServiceName "+"["+serviceName+"]");
	        }
        	
	        
	        if (logger.isDebug()){
	        	logger.debug("JtcClientAdapter] Send Data "+"["+new String(data)+"]");
	        	logger.debug("JtcClientAdapter] Send Data dump "+CommonLib.getDumpMessage(data));
	        	
	        }
	        
	        if (logger.isDebug()){
	        	logger.debug("JtcClientAdapter] BUFFER_TYPE "+"["+bufferType+"]");
	        }
	        TuxBuffer sndbuf = null; 
	        if(DEFAULT_BUFFER_TYPE.equals(bufferType)) {
	        	sndbuf = service.createCarrayBuffer();
	        	sndbuf.setBytes(data);
	        }
	        else if("STRING".equals(bufferType)) {
	        	sndbuf = service.createStringBuffer();
	        	sndbuf.setString(new String(data));
	        }
	        else if("FML".equals(bufferType)) {
	        	// TODO : create table class
	        	//        JSON to FML conversion
	        	//        -> make Converter class (JSON -> FML)  
//	        	sndbuf = service.createFieldBuffer(false, tuxFieldTable);
	        	sndbuf = new TuxFieldBuffer(false);
	        	sndbuf.createField("REQUEST").add(new String(data));
	        }
	        else if("FML32".equals(bufferType)) {
	        	sndbuf = new TuxFieldBuffer(true);
	        	sndbuf.createField("REQUEST").add(new String(data));
	        }
	        else {
	        	throw new Exception("Invalid buffer.type ="+ bufferType);
	        }
	        
	        if ("ASYN".equals(responseType)){
	        	
	        	TuxCallDescripter d = service.tpacall(sndbuf);
				data = null;
		        if (logger.isDebug()){
		        	logger.debug("JtcClientAdapter] Recv Data Async "+"["+d.toString()+"]");
		        }
	        }else{
	        	TuxBuffer rcvbuf = service.tpcall(sndbuf);
	        	
	        	if(DEFAULT_BUFFER_TYPE.equals(bufferType)) {
					byte[] response = rcvbuf.getBytes();
		        	data = response;
		        }
		        else if("STRING".equals(bufferType)) {
		        	String response = rcvbuf.getString();
		        	data = response.getBytes();
		        }
		        else if("FML".equals(bufferType)) {
		        	// TODO : FML to JSON conversion
		        	String response =rcvbuf.getField("RESPONSE").get().stringValue();
		        	data = response.getBytes();
		        }
		        else if("FML32".equals(bufferType)) {
		        	String response =rcvbuf.getField("RESPONSE").get().stringValue();
		        	data = response.getBytes();
		        }
	        	
		        if (logger.isDebug()){
		        	logger.debug("JtcClientAdapter] Recv Data Sync "+"["+new String(data)+"]");
		        	logger.debug("JtcClientAdapter] Recv Data dump "+CommonLib.getDumpMessage(data));
		        }
	        }
        } catch (Exception e){
        	try {
        		String errorCode = "RECEAIOWT001";
        		String addMsg = ", "+e.getMessage()+",["+prop.getProperty(DOMAIN_NAME)+":"+prop.getProperty(SERVICE_NAME)+"]";
        		SMSLogger.loggingSMSWithCode(errorCode, addMsg);
        	} catch(Throwable t){
        		logger.error("[EAIDEBUG] SMS logging Error occured. but ignore this. - " + t.toString());
        	}
        	throw e;
        }finally{

        }	
        
        return data;
    }
}
