package com.eactive.eai.rms.bat.web.eims;

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

import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class EIMSBatParser implements EIMSBatConstants {

	public static void validation(HashMap<String, String> mergeMap) throws Exception {

		String chkStr = null;
		String batchType;

		if (mergeMap.containsKey(EIMSBatConstants.BATCHTYPE)) {
			batchType = mergeMap.get(EIMSBatConstants.BATCHTYPE);
		} else {
			throw new Exception("처리유형(배치유형) 오류[null이거나 길이오류-" + EIMSBatConstants.BATCHTYPE + "]");
		}

		// 인터페이스 필수항목
		if (mergeMap.containsKey(EIMSBatConstants.INTFID)) {
			chkStr = mergeMap.get(EIMSBatConstants.INTFID);
		} else {
			throw new Exception("인터페이스ID 오류[null이거나 길이오류-" + EIMSBatConstants.INTFID + "]");
		}
		if (mergeMap.containsKey(EIMSBatConstants.AUTHORID)) {
			chkStr = mergeMap.get(EIMSBatConstants.AUTHORID);
		} else {
			throw new Exception("사용자ID 오류[null이거나 길이오류-" + EIMSBatConstants.AUTHORID + "]");
		}
		if (mergeMap.containsKey(EIMSBatConstants.SRCAUTHOR)) {
			chkStr = mergeMap.get(EIMSBatConstants.SRCAUTHOR);
		} else {
			throw new Exception("송신담당자ID 오류[null이거나 길이오류-" + EIMSBatConstants.SRCAUTHOR + "]");
		}
		if (mergeMap.containsKey(EIMSBatConstants.TGTAUTHOR)) {
			chkStr = mergeMap.get(EIMSBatConstants.TGTAUTHOR);
		} else {
			throw new Exception("수신담당자ID 오류[null이거나 길이오류-" + EIMSBatConstants.TGTAUTHOR + "]");
		}
		if (mergeMap.containsKey(EIMSBatConstants.SRCBZSYSTEMCD)) {
			chkStr = mergeMap.get(EIMSBatConstants.SRCBZSYSTEMCD);
		} else {
			throw new Exception("송신시스템ID 오류[null이거나 길이오류-" + EIMSBatConstants.SRCBZSYSTEMCD + "]");
		}
		if (mergeMap.containsKey(EIMSBatConstants.TGTBZSYSTEMCD)) {
			chkStr = mergeMap.get(EIMSBatConstants.TGTBZSYSTEMCD);
		} else {
			throw new Exception("수신시스템ID 오류[null이거나 길이오류-" + EIMSBatConstants.TGTBZSYSTEMCD + "]");
		}
		if (mergeMap.containsKey(EIMSBatConstants.APPCD)) {
			chkStr = mergeMap.get(EIMSBatConstants.APPCD);
		} else {
			throw new Exception("인터페이스APPCD 오류[null이거나 길이오류-" + EIMSBatConstants.APPCD + "]");
		}

		// 배치 유형이 DB일 경우 필수 체크 (DB서비스명 및 query)
		if ("DD".equals(batchType)) {
			if (mergeMap.containsKey(EIMSBatConstants.SRCDBEXTRACTQUERY)) {
				chkStr = mergeMap.get(EIMSBatConstants.SRCDBEXTRACTQUERY);
			} else {
				throw new Exception("송신SQL 오류[null이거나 길이오류-" + EIMSBatConstants.SRCDBEXTRACTQUERY + "]");
			}
			if (mergeMap.containsKey(EIMSBatConstants.TGTDBLOADQUERY)) {
				chkStr = mergeMap.get(EIMSBatConstants.TGTDBLOADQUERY);
			} else {
				throw new Exception("수신SQL 오류[null이거나 길이오류-" + EIMSBatConstants.TGTDBLOADQUERY + "]");
			}

			if (mergeMap.get(EIMSBatConstants.TRNSRSLTRFLCTYN) != null
					&& mergeMap.get(EIMSBatConstants.TRNSRSLTRFLCTYN).equals("Y")) {
				if (mergeMap.containsKey(EIMSBatConstants.SRCDBRSLTRFLCTQUERY)) {
					chkStr = mergeMap.get(EIMSBatConstants.SRCDBRSLTRFLCTQUERY);
				} else {
					throw new Exception("결과반영SQL 오류[null이거나 길이오류-" + EIMSBatConstants.SRCDBRSLTRFLCTQUERY + "]");
				}
			}
		}

		// 배치 유형이 파일일 경우 필수 체크(파일패턴 및 상대경로
		if ("FF".equals(batchType)) {
			if (mergeMap.containsKey(EIMSBatConstants.SRCFILENM)) {
				chkStr = mergeMap.get(EIMSBatConstants.SRCFILENM);
			} else {
				throw new Exception("송신File명 오류[null이거나 길이오류-" + EIMSBatConstants.SRCFILENM + "]");
			}

			if (mergeMap.containsKey(EIMSBatConstants.SRCFILEPATH)) {
				chkStr = mergeMap.get(EIMSBatConstants.SRCFILEPATH);
				if (chkStr.indexOf("\\") > 0) {
					throw new Exception("송신원격접속 상대 경로 [파일경로 포멧 오류-" + EIMSBatConstants.SRCFILEPATH + "]");
				}
			} else {
				throw new Exception("송신원격접속 상대 경로 [null이거나 길이오류-" + EIMSBatConstants.SRCFILEPATH + "]");
			}

			if (mergeMap.containsKey(EIMSBatConstants.TGTFILEPATH)) {
				chkStr = mergeMap.get(EIMSBatConstants.TGTFILEPATH);
				if (chkStr.indexOf("\\") > 0) {
					throw new Exception("송신원격접속 상대 경로 [파일경로 포멧 오류-" + EIMSBatConstants.SRCFILEPATH + "]");
				}
			} else {
				throw new Exception("수신원격접속패스 오류 [null이거나 길이오류-" + EIMSBatConstants.TGTFILEPATH + "]");
			}

		}

		if (EIMSBatConstants.EVENTCALLVAL_SCHED.equals(mergeMap.get(EIMSBatConstants.EVENTCALLVAL))) {
			if (EimsBatUtil.isStrEmpty(mergeMap.get(EIMSBatConstants.POLLINGSTRTIME))
					|| EimsBatUtil.isStrEmpty(mergeMap.get(EIMSBatConstants.POLLINGENDTIME))
					|| EimsBatUtil.isStrEmpty(mergeMap.get(EIMSBatConstants.POLLINGCYCLE))) {
				throw new Exception("스케쥴 시간 설정 오류 [null이거나 포맷오류-" + EIMSBatConstants.POLLINGSTRTIME + ","
						+ EIMSBatConstants.POLLINGENDTIME + "," + EIMSBatConstants.POLLINGCYCLE + "]");
			}

		}

	}

	public static HashMap<String, String> parseInfoMap(String data, int keyNum) throws Exception {
		HashMap<String, String> result = new HashMap<String, String>();

		InputStream is = null;

		try {
			is = StringToStream(data);
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(is);

			Element inter = doc.getRootElement();

			result.putAll(getAttr(doc.getRootElement()));

			if (keyNum == EIMSBatConstants.KEYNUM_INTERFACE) { // interface
				result.putAll(getAttr(inter.getChild(HEADER)));
				// ** key: INTERFACE 처리

			} else if (keyNum == EIMSBatConstants.KEYNUM_DBTODB) { // DBtoDB
				// ** key: DBtoDB 처리
				result.putAll(getAttr(inter.getChild(DBSEND)));

				result.putAll(getAttr(inter.getChild(DBRECV)));

			} else if (keyNum == EIMSBatConstants.KEYNUM_FLIETOFILE) { // FiletoFile
				// ** key: FiletoFile 처리
				result.putAll(getAttr(inter.getChild(FILESEND)));

				result.putAll(getAttr(inter.getChild(FILERECV)));

			}

		} catch (Exception e) {
			throw new Exception("[" + keyNum + "] XML parsing error " + e.getMessage(), e);
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (Exception e) {
				}
			}
		}
		return result;
	}

	/**
	 * attr 추출
	 * 
	 * @param doc
	 * @return
	 */
	public static HashMap<String, String> getAttr(Element doc) {
		if (doc == null)
			return new HashMap<String, String>();
		HashMap<String, String> map = new HashMap<String, String>();
		for (Object obj : doc.getAttributes()) {
			if (obj instanceof Attribute) {
				Attribute attr = (Attribute) obj;
				map.put(attr.getName(), attr.getValue());
			}
		}
		return map;
	}

	/**
	 * stream 변환
	 * 
	 * @param s
	 * @return
	 */
	public static InputStream StringToStream(String s) {
		ByteArrayInputStream buffer = null;
		try {
			buffer = new ByteArrayInputStream(s.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	/**
	 * 버전 앞에 0채우기.
	 * 
	 * @param ver
	 * @return
	 */
	public static String parseVerInfo(String ver) {
		String ret = "";
		int verLen = ver.length();
		int zeroCnt = 5 - verLen; // verInfo Default -> 00000
		for (int i = 0; i < zeroCnt; i++) {
			ret += "0";
		}
		ret += ver;
		return ret;
	}
}