package com.eactive.eai.transformer;

import java.util.ArrayList;
import java.util.List;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import com.eactive.eai.common.util.Logger;
import com.eactive.eai.transformer.engine.TransformEngine;
import com.eactive.eai.transformer.engine.Transformer;
import com.eactive.eai.transformer.function.util.CodeConversion;
import com.eactive.eai.transformer.layout.Item;
import com.eactive.eai.transformer.message.JSONMessage;
import com.eactive.eai.transformer.message.Message;
import com.eactive.eai.transformer.message.MessageFactory;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;


public class TransformJsonTest extends TestCase {
	protected static Logger logger = Logger.getLogger("transformer");

	TransformEngine engine = null;
    
    
    public TransformJsonTest(String name) {
        super(name);
    }

    public static Test suite() {
        /*
        * the dynamic way
        */
        return new TestSuite(TransformJsonTest.class);
    }

    public void setUp() throws Exception {
        // 변환 초기화
        engine = TransformEngine.getInstance();

        if (!engine.isStarted()) {
            engine.start();
        }
    }

    public void tearDown() throws Exception {
        //
    }

//    public void testJsonToFlatTransform() throws Exception {
//        //logger.debug("Transform08900001Test | testTransform()");
//
//        //----------------------------------------------------------------------
//        // source message 생성
//        //----------------------------------------------------------------------
//    	String data ="{\"EAI\":{\"INDIVIDUAL\":{\"addr\":\"\",\"deptNm\":\"D\",\"deptCd\":\"12000\",\"email\":\"\",\"telNo\":\"\"},\"COMMON\":{\"empNo\":\"0200\"}}}";
//    	
//        Message source = MessageFactory.getFactory().getMessage("TST_JSN0400KEDS2_REQ1");
//        source.setData(data.getBytes());
//        System.out.println(source);
//
//        //----------------------------------------------------------------------
//        // 변환 방식 1
//        //----------------------------------------------------------------------
//        Transformer transformer = engine.getTransformer();
//        Message target = transformer.transform("TRANSFORM_TST_JSN0400KEDS2_REQ", new Message[] { source });
//
////        System.out.println(target);
//        System.out.println(target.toString());
//        
//    }
 
//    public void testFlatToJsonTransform() throws Exception {
//
//        //----------------------------------------------------------------------
//        // source message 생성
//        //----------------------------------------------------------------------
//    	String data ="0200      12000               D                                                                                                                       ";
//        Message source = MessageFactory.getFactory().getMessage("TST_JSN0400KEDS2_RES1");
//        source.setData(data.getBytes());
//        System.out.println(source);
//
//        //----------------------------------------------------------------------
//        // 변환 방식 1
//        //----------------------------------------------------------------------
//        Transformer transformer = engine.getTransformer();
//        Message target = transformer.transform("TRANSFORM_TST_JSN0400KEDS2_RES", new Message[] { source });
//
//        
////        System.out.println(target);
//        System.out.println(target.toString());
//        System.out.println("testFlatToJsonTransform >> [["+target.getData()+"]]");
//        
//    }    
    
    
//    public void testJsonToFlatTransform2() throws Exception {
//  		System.out.println("Json TO Flat ==============================================================");
//        //logger.debug("Transform08900001Test | testTransform()");
//
//        //----------------------------------------------------------------------
//        // source message 생성
//        //----------------------------------------------------------------------
//    	String data ="";
//    	data = "{\"TST_CCMMCI0023RS1JBB_REQ1\":{\"INDIVIDUAL\":{\"user_div_cd\":\"00\",\"ogz_cd\":\"\",\"user_no\":\"\",\"page_no\":\"00001\",\"user_nm\":\"\",\"page_row_size\":\"00023\"}}}";
//
//    	data = "{\"user_div_cd\":\"00\",\"ogz_cd\":\"\",\"user_no\":\"\",\"page_no\":\"00001\",\"user_nm\":\"\",\"page_row_size\":\"00023\"}";
//    	
//        Message source = MessageFactory.getFactory().getMessage("TST_CCMMCI0023RS1JBB_REQ1");
//        
//		String rootItemName = ((JSONMessage)source).getLayout().getRootItem().getName();
//
//        JSONObject value = (JSONObject)JSONValue.parse(data);
//        JSONObject root = new JSONObject();
//        root.put(rootItemName, value);
//        data = root.toJSONString();    
//
//
//        source.setData(data.getBytes());
////        System.out.println("source="+source);
//
//        //----------------------------------------------------------------------
//        // 변환 방식 1
//        //----------------------------------------------------------------------
//        Transformer transformer = engine.getTransformer();
//        Message target = transformer.transform("TRANSFORM_TST_CCMMCI0023RS1_REQ", new Message[] { source });
//
//        System.out.println(target.toString());
////        
//    }
//  public void testFlatToJsonTransform2() throws Exception {
//	  		System.out.println("Flat TO Json ==============================================================");
//            //----------------------------------------------------------------------
//            // source message 생성
//            //----------------------------------------------------------------------
//        	String data ="00                                                                                                                    0000100023";
//            Message source = MessageFactory.getFactory().getMessage("TST_CCMMCI0023RS1JBB_REQ2");
//            source.setData(data.getBytes());
////            System.out.println(source);
//    
//            //----------------------------------------------------------------------
//            // 변환 방식 1
//            //----------------------------------------------------------------------
//            Transformer transformer = engine.getTransformer();
//            Message target = transformer.transform("TRANSFORM_TST_CCMMCI9999S1_RES", new Message[] { source });
//    
//            
////            System.out.println(target);
//            System.out.println(target.toString());
//            System.out.println("testFlatToJsonTransform >> [["+target.getData()+"]]");
//            
//        }        
    
    
	public void atestJsonToFlatTransform2() throws Exception {
		System.out.println("Json TO Flat ==============================================================");
		// logger.debug("Transform08900001Test | testTransform()");

		// ----------------------------------------------------------------------
		// source message 생성
		// ----------------------------------------------------------------------
		String data = "";
    	data = "{\"ApprovalCancelKB\":{\"Common\":{\"Sender\":\"Sender\",\"TransactionSEQNO\":\"TransactionSEQNO\", \"Receiver\":\"100\"}}}";


		Message source = MessageFactory.getFactory().getMessage("LEN_BBSD115_TSTS");
		
		//LEN_BBSD115_BYTS
		
		

		String rootItemName = ((JSONMessage) source).getLayout().getRootItem().getName();

		JSONObject value = (JSONObject) JSONValue.parse(data);
		JSONObject root = new JSONObject();
		root.put(rootItemName, value);
		data = root.toJSONString();
		System.out.println(data);
		source.setData(data.getBytes());
		System.out.println(source.getData());
		
      Transformer transformer = engine.getTransformer();
      Message target = transformer.transform("TRANSFORM_LEN_BBSD115S1_ERR", new Message[] { source });
      
      System.out.println("["+new String((byte[])target.getData())+"]");

	} 

	public void atestUJsonToUJsonTransform2() throws Exception {
		System.out.println("Json TO Json ==============================================================");
		// logger.debug("Transform08900001Test | testTransform()");
		
		// ----------------------------------------------------------------------
		// source message 생성
		// ----------------------------------------------------------------------
		String data = "";
		data = "{\"OutChnlTxCd\":\"BFB72P90S7\",\"OutForms\":[],\"OutData\":{\"총라인수\":10,\"장바구니_그리드\":[{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190208110141\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00003600\",\"상품코드\":\"\",\"상품명\":\"KB 브라질 증권 자투자신탁(주식)-C\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190208110131\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00003500\",\"상품코드\":\"\",\"상품명\":\"KB 브라질 증권 자투자신탁(주식)-A\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190207135711\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00169600\",\"상품코드\":\"\",\"상품명\":\"KB 브라질 증권 자투자신탁(주식)-AE\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190129174634\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00114800\",\"상품코드\":\"\",\"상품명\":\"한화 글로벌 멀티인컴 증권자투자신탁(주식혼합-재간접형)C-E\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190129174256\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00131100\",\"상품코드\":\"\",\"상품명\":\"KB 가치배당 40 증권 자투자신탁(채권혼합)-Ce\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190129173619\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00100500\",\"상품코드\":\"\",\"상품명\":\"미래에셋 월지급식 글로벌 다이나믹 플러스 증권자투자신탁 1호(채권) AE\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190129173330\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00111600\",\"상품코드\":\"\",\"상품명\":\"슈로더 월지급 아시안 에셋 인컴 증권투자신탁(주식혼합-재간접형) C-e\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190129171841\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00038800\",\"상품코드\":\"\",\"상품명\":\"KB스타 개인용 MMF P-101호(국공채)A-EU\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190129171614\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00038600\",\"상품코드\":\"\",\"상품명\":\"KB스타 미국S＆P500인덱스 증권자투자신탁(주식-파생형)A-EU\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"},{\"고객식별자\":\"1098428265\",\"고객관리번호\":\"00000\",\"장바구니일련번호\":\"\",\"담기일자\":\"20190129170422\",\"상품분류체계코드\":\"CN00000000\",\"상품분류상세코드\":\"KF00201400\",\"상품코드\":\"\",\"상품명\":\"KB PIMCO 글로벌 인컴 셀렉션 증권투자신탁(채권-재간접형)(H) AE\",\"등록채널명\":\"고객(비대면장바구니)\",\"등록부점코드\":\"\",\"등록부점명\":\"인터넷뱅킹\",\"등록직원번호\":\"\",\"등록직원명\":\"고객\"}]}}";
		Message source = MessageFactory.getFactory().getMessage("BFB_BFB72P90S7_RES1");
		//LEN_BBSD115_BYTS
		String rootItemName = ((JSONMessage) source).getLayout().getRootItem().getName();
		JSONObject value = (JSONObject) JSONValue.parse(data);
		JSONObject root = new JSONObject();
		root.put(rootItemName, value);
		data = root.toJSONString();
		System.out.println(data);
		System.out.println(source);
		source.setData(data.getBytes("UTF-8"));
		System.out.println(source.getData());
			
		Transformer transformer = engine.getTransformer();
		Message target = transformer.transform("TRANSFORM_BNE_BFB72P90S7BNE_RES", new Message[] { source });
		System.out.println("["+new String((byte[])target.getData())+"]");

	} 
    
	public void testUJsonToXmlTransform() throws Exception {
		System.out.println("Json TO Xml ==============================================================");
	
		// ----------------------------------------------------------------------
		// source message 생성
		// ----------------------------------------------------------------------
		String data = "";
		data = "{\"InData\":{\"변경전상호명\":\"\",\"일반공모시작년월일\":\"\",\"기산년월일\":\"20200101\",\"일반공모종료년월일\":\"\",\"보증여부\":\"0\",\"통화코드\":\"KRW\",\"보증기관명\":\"\",\"우리사주배정비율\":0,\"신주인수권증서발행여부\":\"0\",\"교부년월일\":\"20200703\",\"발행사유\":\"2103\",\"사채발행년월일\":\"\",\"우리사주배정주식\":0,\"만기년월일\":\"\",\"시스템최종사용자번호\":\"\",\"구주청약시작년월일\":\"\",\"주간사\":\"국민은행\",\"발행총액\":0,\"교체주권종류구분내용\":\"1000000000000000000000000000000000000000\",\"전환대리인명\":\"\",\"거래사유\":\"\",\"기준년월일\":\"20200331\",\"단주확정방법\":\"9\",\"신주인수권증서\":\"\",\"확정배정비율수2\":100,\"차등배정여부\":\"0\",\"예정비율\":0,\"전환청구종료년월일\":\"\",\"전환청구시작년월일\":\"\",\"청구횟수\":0,\"단주대금가\":60000,\"사채원리금지급대행은행코드\":\"\",\"주금납입년월일\":\"20200703\",\"장기보유세금감면여부\":\"0\",\"주권구분\":\"01\",\"기등록사채여부\":\"0\",\"상장년월일\":\"20200704\",\"전환가격\":0,\"발행이율\":0,\"주?납입금융기관코드\":\"\",\"전환후주식수\":0,\"위탁회사번호\":\"04692\",\"구주청약종료년월일\":\"\",\"신권당일유통년월일\":\"\",\"구주권제출시작년월일\":\"\",\"발행가\":0,\"권면금액\":0,\"시스템최종처리일시\":\"\",\"무배정여부\":\"0\",\"발행회차\":7,\"문서접수년월일\":\"20200703\",\"통지서발송비대상\":\"0\",\"변경후영문상호명\":\"\",\"변경후상호명\":\"\",\"사채명\":\"\",\"주권종류\":\"01\",\"잔여금액\":0,\"명의개서정지시작년월일\":\"20200401\",\"단주대금년월일\":\"20200703\",\"명의개서정지종료년월일\":\"20200402\",\"전환주식수\":0,\"전환환율\":0,\"문서번호\":\"증권대행부\",\"예정가\":0,\"기준환율\":0,\"사채통화코드\":\"KRW\",\"확정가\":0,\"피발행회차\":\"0\",\"우리사주배정비율수2\":100,\"전환전주식수\":0,\"구주권제출종료년월일\":\"\",\"과세비율\":0,\"확정비율\":0,\"차등배정비율수1\":0,\"차등배정비율수2\":100,\"용지신청년월일\":\"99991231\",\"피회사번호\":\"00000\",\"발행년월일\":\"20200703\",\"액면가\":5000,\"사채발행회차\":0,\"납입장소\":\"국민은행 여의도본점\",\"회사명\":\"=한=NF매제상하\",\"전환회차\":0,\"주권유통종료년월일\":\"\",\"예정배정비율수2\":100,\"기준환율등록년월일\":\"\",\"사용자구분\":\"\",\"주권유통시작년월일\":\"\",\"변경후액면가\":0,\"우리청약시작년월일\":\"\",\"거래구분\":\"0\",\"구회사명\":\"\",\"발행주수\":100,\"증자방법\":\"00\",\"우리청약종료년월일\":\"\",\"변경전액면가\":0,\"주관회사명\":\"\",\"기타내용1\":\"\",\"신종사채해외여부\":\"0\",\"청약장소\":\"한국투자증권본지점\"}}";
		Message source = MessageFactory.getFactory().getMessage("BFG_KGB0690761_REQ1");
		//LEN_BBSD115_BYTS
		String rootItemName = ((JSONMessage) source).getLayout().getRootItem().getName();
		JSONObject value = (JSONObject) JSONValue.parse(data);
		JSONObject root = new JSONObject();
		root.put(rootItemName, value);
		data = root.toJSONString();
		System.out.println(data);
		System.out.println(source);
		source.setData(data.getBytes("UTF-8"));
		System.out.println(source.getData());
			
		Transformer transformer = engine.getTransformer();
		Message target = transformer.transform("TRANSFORM_BFG_KGB0690761BFG_REQ", new Message[] { source });
		
		System.out.println("["+target.getData()+"]");
		System.out.println(target);
		
		Item item = target;
		ArrayList alist = getItemInfo(item, 0 ,false );
		
	}
	
	public ArrayList getItemInfo(Item sitem, int path, boolean isEbcdic) {
		ArrayList alist = new ArrayList();
		String field_delimiter = "^FLD^";

		StringBuffer sb = new StringBuffer();
		if (sitem.getNodeTypeId() == Item.NODE_MESSAGE
				|| sitem.getNodeTypeId() == Item.NODE_GROUP) {
			sb.append(sitem.getName());
			sb.append(field_delimiter);
			sb.append(sitem.getDescription());
			sb.append(field_delimiter);
			
			Object obj = sitem.getValue();
			String value = "";
			System.out.println(sitem.getName() + "-> " + obj);
			if (obj == null) {
				value = " ";
			} else if (obj instanceof String) {
				value = new String(((String) obj).getBytes());
			} else if (obj instanceof byte[]) {
				if(isEbcdic) {
					value = new String(CodeConversion.meToAsc2((byte[]) obj));
				}
				else {
					value = new String((byte[]) obj);
				}
				
			} else {
				value = "";
			}

			sb.append(value);

			sb.append(field_delimiter);
			sb.append(" ");

			alist.add(sb.toString());

			List list = sitem.getChildList();
			path++;
			for (int i = 0; i < list.size(); i++) {
				//System.out.println("LOOP ["+path+"]["+i+"]["+ ((Item)list.get(i)).getName() +"]");                    
				if (!((Item) list.get(i)).toString("", false).equals("")) {
					ArrayList slist = getItemInfo((Item) list.get(i), path , isEbcdic);
					for (int j = 0; j < slist.size(); j++) {
						alist.add((String) slist.get(j));
					}
				}
			}
		} else {
			sb.append(sitem.getName());
			sb.append(field_delimiter);
			sb.append(sitem.getDescription());
			sb.append(field_delimiter);
			Object obj = sitem.getValue();
			
			System.out.println(sitem.getName() + "-> " + obj);
			
			String value = "";
			if (obj == null) {
				value = "NULL";
			} else if (obj instanceof String) {
				value = new String(((String) obj).getBytes());
			} else if (obj instanceof byte[]) {
//				if(isEbcdic) {
//					value = new String(CodeConversion.meToAsc2((byte[]) obj));
//				}
//				else {
					value = new String((byte[]) obj);
//				}
			} else {
				value = "";
			}

			sb.append(value);

			sb.append(field_delimiter);
			sb.append("" + sitem.getLength());

			alist.add(sb.toString());
		}
		return alist;
	}
}
