package com.eactive.eai.rms.onl.transaction.tracking;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;


public class STDXmlParser {
	private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
	private static Logger logger = Logger.getLogger(STDXmlParser.class);
	public static void main(String[] args) throws Exception{
		String data = 
				"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
				"       <STD_SYSTEMHEADER_REQ desc=\"표준전문-시스템헤더\">\r\n" + 
				"           <VRSN desc=\"버전\" length=\"3\"></VRSN>\r\n" + 
				"           <INPT_OUPT_DVSN_CODE desc=\"입력출력구분코드\" length=\"1\">I</INPT_OUPT_DVSN_CODE>\r\n" + 
				"           <VFST_GUID desc=\"최초GUID\" length=\"38\">CBK20210312121212000ieaiinst1100000001</VFST_GUID>\r\n" + 
				"           <GUID desc=\"GUID\" length=\"38\">CBK20210312121212000ieaiinst1100000001</GUID>\r\n" + 
				"           <PRGR_SQNU desc=\"진행일련번호\" length=\"4\">0</PRGR_SQNU>\r\n" + 
				"           <TLGR_CRYP_YN desc=\"전문암호화여부\" length=\"1\"></TLGR_CRYP_YN>\r\n" + 
				"           <CHNL_DVSN desc=\"채널구분\" length=\"2\"></CHNL_DVSN>\r\n" + 
				"           <IP_VRSN_DVSN_CODE desc=\"IP버전구분코드\" length=\"2\"></IP_VRSN_DVSN_CODE>\r\n" + 
				"           <FRST_RQUT_SYS_IP desc=\"최초요청시스템IP\" length=\"39\"></FRST_RQUT_SYS_IP>\r\n" + 
				"           <FRST_RQUT_SYS_MAC desc=\"최초요청시스템MAC\" length=\"17\"></FRST_RQUT_SYS_MAC>\r\n" + 
				"           <ENVR_INFO_DVSN_CODE desc=\"환경정보구분코드\" length=\"1\">D</ENVR_INFO_DVSN_CODE>\r\n" + 
				"           <FRST_RQUT_SYS_CODE desc=\"최초요청시스템코드\" length=\"3\"></FRST_RQUT_SYS_CODE>\r\n" + 
				"           <TRAN_SYS_CODE desc=\"전송시스템코드\" length=\"3\"></TRAN_SYS_CODE>\r\n" + 
				"           <MCI_IF_ID desc=\"MCI_인터페이스ID\" length=\"15\">MITTCBK00000009</MCI_IF_ID>\r\n" + 
				"           <MCI_IF_SESN_ID desc=\"MCI_인터페이스세션ID\" length=\"40\"></MCI_IF_SESN_ID>\r\n" + 
				"           <MCI_IF_NODE_ID desc=\"MCI_인터페이스노드ID\" length=\"2\"></MCI_IF_NODE_ID>\r\n" + 
				"           <EAI_IF_ID desc=\"EAI_인터페이스ID\" length=\"15\"></EAI_IF_ID>\r\n" + 
				"           <EAI_IF_SESN_ID desc=\"EAI_인터페이스세션ID\" length=\"40\"></EAI_IF_SESN_ID>\r\n" + 
				"           <EAI_IF_NODE_ID desc=\"EAI_인터페이스노드ID\" length=\"2\"></EAI_IF_NODE_ID>\r\n" + 
				"           <FEP_IF_ID desc=\"FEP_인터페이스ID\" length=\"15\"></FEP_IF_ID>\r\n" + 
				"           <FEP_IF_SESN_ID desc=\"FEP_인터페이스세션ID\" length=\"40\"></FEP_IF_SESN_ID>\r\n" + 
				"           <FEP_IF_NODE_ID desc=\"FEP_인터페이스노드ID\" length=\"2\"></FEP_IF_NODE_ID>\r\n" + 
				"           <FRST_TLGR_RQUT_DATE desc=\"최초전문요청일시\" length=\"17\">20210312100000000</FRST_TLGR_RQUT_DATE>\r\n" + 
				"           <RQUT_SYS_CODE desc=\"요청시스템코드\" length=\"3\"></RQUT_SYS_CODE>\r\n" + 
				"           <RQUT_SYS_NODE_ID desc=\"요청시스템노드ID\" length=\"3\"></RQUT_SYS_NODE_ID>\r\n" + 
				"           <TLGR_RQUT_DATE desc=\"전문요청일시\" length=\"17\">20210312100000000</TLGR_RQUT_DATE>\r\n" + 
				"           <TX_PROC_DVSN_CODE desc=\"거래처리구분코드\" length=\"1\"></TX_PROC_DVSN_CODE>\r\n" + 
				"           <RESP_SYS_CODE desc=\"응답시스템코드\" length=\"3\"></RESP_SYS_CODE>\r\n" + 
				"           <TLGR_RESP_DATE desc=\"전문응답일시\" length=\"17\"></TLGR_RESP_DATE>\r\n" + 
				"           <RESP_RSLT_DVSN_CODE desc=\"응답결과구분코드\" length=\"1\"></RESP_RSLT_DVSN_CODE>\r\n" + 
				"           <MULTILNG_DVSN_CODE desc=\"다국어구분코드\" length=\"2\"></MULTILNG_DVSN_CODE>\r\n" + 
				"           <MSG_CHNL_DVSN desc=\"메시지채널구분\" length=\"2\"></MSG_CHNL_DVSN>\r\n" + 
				"           <TX_ID desc=\"거래ID\" length=\"10\">ATDCI00010</TX_ID>\r\n" + 
				"           <CANL_TX_YN desc=\"취소거래여부\" length=\"1\"></CANL_TX_YN>\r\n" + 
				"           <TLGR_TYPE_CODE desc=\"전문 유형코드\" length=\"1\"></TLGR_TYPE_CODE>\r\n" + 
				"           <LVOL_DATA_PROC_DVSN_CODE desc=\"대량데이터처리구분코드\" length=\"1\"></LVOL_DATA_PROC_DVSN_CODE>\r\n" + 
				"           <LVOL_DATA_PROC_SERI_SEQ desc=\"대량데이터처리일련번호\" length=\"4\">0</LVOL_DATA_PROC_SERI_SEQ>\r\n" + 
				"           <SMLT_TX_DVSN_CODE desc=\"시뮬레이션 거래 구분코드\" length=\"1\"></SMLT_TX_DVSN_CODE>\r\n" + 
				"           <ACNT_MODE_DVSN_CODE desc=\"계정모드 구분코드\" length=\"1\"></ACNT_MODE_DVSN_CODE>\r\n" + 
				"           <NORM_RESP_RCVM_TX_ID desc=\"정상응답수신거래ID\" length=\"10\"></NORM_RESP_RCVM_TX_ID>\r\n" + 
				"           <OUTR_TX_TIMR_ACTN_KEY desc=\"대외거래TIMER실행키\" length=\"50\"></OUTR_TX_TIMR_ACTN_KEY>\r\n" + 
				"           <ERR_RESP_RCVM_TX_ID desc=\"오류응답수신거래ID\" length=\"10\"></ERR_RESP_RCVM_TX_ID>\r\n" + 
				"       </STD_SYSTEMHEADER_REQ>\r\n" + 
				"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
				"       <STD_COMMONHEADER_REQ desc=\"표준전문-공통헤더\">\r\n" + 
				"           <ROFC_CODE desc=\"청코드\" length=\"2\"></ROFC_CODE>\r\n" + 
				"           <BRN_CODE desc=\"국코드\" length=\"6\"></BRN_CODE>\r\n" + 
				"           <TRMT_ROFC_CODE desc=\"취급청코드\" length=\"2\"></TRMT_ROFC_CODE>\r\n" + 
				"           <TRMT_BRN_CODE desc=\"취급국코드\" length=\"6\"></TRMT_BRN_CODE>\r\n" + 
				"           <TX_TRMN_NO desc=\"거래단말번호\" length=\"8\"></TX_TRMN_NO>\r\n" + 
				"           <USER_ID desc=\"사용자ID\" length=\"9\">TEST00001</USER_ID>\r\n" + 
				"           <RSPS_APRV_PROC_CODE desc=\"책임자승인처리코드\" length=\"1\">R</RSPS_APRV_PROC_CODE>\r\n" + 
				"           <RSPS_APRV_ORDR desc=\"책임자승인차수\" length=\"1\"></RSPS_APRV_ORDR>\r\n" + 
				"           <approveCodeList desc=\"책임자승인코드 목록 시작\">\r\n" + 
				"               <RSPS_APRV_CODE desc=\"책임자승인코드\" length=\"8\"></RSPS_APRV_CODE>\r\n" + 
				"               <RSPS_APRV_RESN desc=\"책임자승인사유\" length=\"300\"></RSPS_APRV_RESN>\r\n" + 
				"           </approveCodeList>\r\n" + 
				"           <approveList desc=\"책임자승인 목록 시작\">\r\n" + 
				"               <RSPS_APRV_DVSN_CODE desc=\"책임자승인구분코드\" length=\"2\"></RSPS_APRV_DVSN_CODE>\r\n" + 
				"               <APRV_USER_ID desc=\"승인사용자ID\" length=\"9\">TEST00001</APRV_USER_ID>\r\n" + 
				"               <APRV_TRMN_NO desc=\"승인단말번호\" length=\"8\"></APRV_TRMN_NO>\r\n" + 
				"               <RSPS_TX_DVSN_CODE desc=\"책임자거래구분코드\" length=\"2\"></RSPS_TX_DVSN_CODE>\r\n" + 
				"               <LGIN_YN desc=\"로그인여부\" length=\"1\"></LGIN_YN>\r\n" + 
				"               <APRV_RQUT_MSG desc=\"승인요청메시지\" length=\"300\"></APRV_RQUT_MSG>\r\n" + 
				"               <APRV_MEAN_CODE desc=\"승인수단코드\" length=\"1\"></APRV_MEAN_CODE>\r\n" + 
				"               <APRV_RSLT_CODE desc=\"승인결과코드\" length=\"1\"></APRV_RSLT_CODE>\r\n" + 
				"               <APRV_RSLT_MSG desc=\"승인결과메시지\" length=\"300\"></APRV_RSLT_MSG>\r\n" + 
				"           </approveList>\r\n" + 
				"           <MSG_MARK_DVSN_CODE desc=\"메시지표시구분코드\" length=\"1\"></MSG_MARK_DVSN_CODE>\r\n" + 
				"           <messageList desc=\"메시지 목록 시작 (1~10)\">\r\n" + 
				"               <MSG_CODE desc=\"메시지코드\" length=\"10\"></MSG_CODE>\r\n" + 
				"               <MSG_CNTT desc=\"메시지내용\" length=\"300\"></MSG_CNTT>\r\n" + 
				"               <MSRS_MSG_CNTT desc=\"조치메시지내용\" length=\"300\"></MSRS_MSG_CNTT>\r\n" + 
				"               <ERR_PGM_NM desc=\"오류프로그램명\" length=\"100\"></ERR_PGM_NM>\r\n" + 
				"               <ERR_PGM_LINE_NO desc=\"오류프로그램라인번호\" length=\"8\">0</ERR_PGM_LINE_NO>\r\n" + 
				"           </messageList>\r\n" + 
				"       </STD_COMMONHEADER_REQ>\r\n" + 
				"<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
				"       <STD_DATAHEADER_REQ desc=\"표준전문-데이터헤더\">\r\n" + 
				"           <terminalInfo desc=\"단말정보\">\r\n" + 
				"               <SCRN_ID desc=\"화면ID\" length=\"10\"></SCRN_ID>\r\n" + 
				"               <SCRN_CALL_NO desc=\"화면호출번호\" length=\"5\"></SCRN_CALL_NO>\r\n" + 
				"               <CURY_RAMT desc=\"통화잔액\" length=\"15\">0</CURY_RAMT>\r\n" + 
				"               <TRSF_RAMT desc=\"대체잔액\" length=\"15\">0</TRSF_RAMT>\r\n" + 
				"               <OTBC_RAMT desc=\"타점권잔액\" length=\"15\">0</OTBC_RAMT>\r\n" + 
				"               <TRSF_NSAM_YN desc=\"대체불일치여부\" length=\"1\"></TRSF_NSAM_YN>\r\n" + 
				"               <PUSH_DVSN_CODE desc=\"Push구분코드\" length=\"1\">S</PUSH_DVSN_CODE>\r\n" + 
				"           </terminalInfo>\r\n" + 
				"           <noneFacingInfo desc=\"비대면정보\">\r\n" + 
				"           </noneFacingInfo>\r\n" + 
				"           <atmInfo desc=\"ATM정보\">\r\n" + 
				"           </atmInfo>\r\n" + 
				"           <callCenterInfo desc=\"콜센터정보\">\r\n" + 
				"           </callCenterInfo>\r\n" + 
				"           <externalInfo desc=\"대외정보\">\r\n" + 
				"               <OUTR_INST_CODE desc=\"대외기관코드\" length=\"5\"></OUTR_INST_CODE>\r\n" + 
				"               <OUTR_TX_OIWD_DVSN_CODE desc=\"대외거래당타발구분코드\" length=\"1\"></OUTR_TX_OIWD_DVSN_CODE>\r\n" + 
				"           </externalInfo>\r\n" + 
				"           <centerCutInfo desc=\"센터컷정보\">\r\n" + 
				"               <CC_ID desc=\"센터컷ID\" length=\"9\"></CC_ID>\r\n" + 
				"               <CC_PROC_YMD desc=\"센터컷처리일자\" length=\"8\"></CC_PROC_YMD>\r\n" + 
				"               <CC_PROC_TMS desc=\"센터컷처리회차\" length=\"5\">0</CC_PROC_TMS>\r\n" + 
				"               <CC_PROC_SQNU desc=\"센터컷처리일련번호\" length=\"9\">0</CC_PROC_SQNU>\r\n" + 
				"               <CC_PROC_DVSN_CODE desc=\"센터컷처리구분코드\" length=\"2\"></CC_PROC_DVSN_CODE>\r\n" + 
				"               <CC_PROC_RSLT_CODE desc=\"센터컷처리결과코드\" length=\"2\"></CC_PROC_RSLT_CODE>\r\n" + 
				"           </centerCutInfo>\r\n" + 
				"       </STD_DATAHEADER_REQ>\r\n";
		
		HashMap<String,Object> result = new HashMap<String,Object>();
		result=getData(data);
		//logger.debug(result);
		
	}
	public static HashMap<String,Object> getData(String data) throws Exception{
		HashMap<String,Object> vo = new HashMap<String,Object>();
		List<String> splitData = xmlSplit(data);
		for(String xmlData : splitData ) {
			HashMap<String,Object> xmlRow = xmlParse(xmlData);
			String name =(String)xmlRow.get("name");
			List<HashMap<String,Object>> list = (List<HashMap<String,Object>>)xmlRow.get("list");
			vo.put(name,list);
		}
		return vo;
	}
	private static List<String> xmlSplit(String data)throws Exception{

		String xmlData = data;
		String strData = "";		
		ArrayList<String> sptXmlData = new ArrayList<String>();
		int idx = xmlData.indexOf(XML_HEADER);
		int startIdx = 0;
		int endIdx = 0;
		while ( idx  >= 0 ){
			if(idx==0){
				idx=xmlData.indexOf(XML_HEADER,1);
				endIdx = idx-1;
				if(idx==-1){
					idx=xmlData.indexOf(XML_HEADER,0);
					endIdx = xmlData.length();
				}
			}else{
				startIdx = idx-1;
				idx=xmlData.indexOf(XML_HEADER,idx);
				
				endIdx = idx-1;
				if(idx==-1){
					idx=xmlData.indexOf(XML_HEADER,startIdx);
					endIdx = xmlData.length();
					if(startIdx==idx){
						strData = xmlData.substring(startIdx, endIdx);
						if(strData.length()>0){
							sptXmlData.add(strData);
							//logger.debug(strData);
						}
						break;
					}
				}
			}
			idx++;
			
			strData = xmlData.substring(startIdx, endIdx);
			if(strData.length()>0){
				sptXmlData.add(strData);
				//logger.debug(strData);
			}
		}

		return sptXmlData;

	}
	private static HashMap<String,Object> xmlParse(String data) throws Exception{
		HashMap<String,Object> vo = new HashMap<String,Object>();
		
    	InputStream is = null;
    	try { 
    		is = StringToStream(data,"utf-8");
			SAXBuilder builder = new SAXBuilder();
	        Document doc = builder.build(is);
	
	        Element format = doc.getRootElement();
	        
	        
	        String name = format.getName();
	        String desc = format.getAttributeValue("desc");
	        
	        List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
	        list.addAll(xmlDataParse(format));
	        vo.put("name",name);
	        vo.put("desc",desc);
	        vo.put("list", list);
		}catch(Exception e){
			throw new Exception("layout parsing error "+e.getMessage(),e);
    	}finally{
    		if (is != null){try{is.close();}catch(Exception e ){}}
    	}
    	return vo;
		
	}
	private static List<HashMap<String,Object>> xmlDataParse(Element e) throws Exception {
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();

        List<Element> items = e.getChildren();
        for(Element el : items) {
            HashMap<String,Object> item = new HashMap<String,Object>();

            item.put("fieldName",el.getName());
            item.put("korName",el.getAttributeValue("desc"));
            item.put("dataLen", el.getAttributeValue("length"));
            item.put("data",el.getTextTrim());
            list.add(item);
            if( el.getChildren() != null && el.getChildren().size() > 0 ) {
            	list.addAll(xmlDataParse(el));
            }
        }  // end FOR
		
		return list;
	}
	private static InputStream StringToStream(String s, String encoding) throws UnsupportedEncodingException{
		ByteArrayInputStream buffer = new ByteArrayInputStream(s.getBytes(encoding));
		return buffer;
	}

}

