package com.dbs.mplus.service.mobile.consent;

import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.dbs.mplus.framework.FrameworkConstants;
import com.dbs.mplus.framework.util.ConvertUtil;

/**
 * 동의서 Data XML 을 분석한다. 
 * 
 * 
 * @author siyoung.ahn
 *
 */
public class ConsentParser {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	private Map<String, Object> resultMap;
	
	/**
	 * 생성자  
	 * @param obj
	 */
	public ConsentParser(String xmlData) {
		resultMap = this.convert(xmlData);
	}

	public Map<String, Object> getResult() { 
		return this.resultMap;
	}
	
	
	/**
	 * XML 형태의 String을 Map형태로 변환 
	 * @param obj
	 * @return
	 */
//	@SuppressWarnings("unchecked")
	private Map<String, Object> convert(String xmlData) { 
		final Map<String, Object> result = new HashMap<String, Object>(); 
		
		try {
			DocumentBuilderFactory factory  =  DocumentBuilderFactory.newInstance();
			DocumentBuilder builder =  factory.newDocumentBuilder();
			
			Document document =  builder.parse(new InputSource(new StringReader(xmlData)));
			
			for (ConsentItem consentItem : ConsentItem.values()) {
				// XML 데이터에서 값 추출
				NodeList nodelist = document.getElementsByTagName(consentItem.getDataName());
				if(nodelist.getLength() > 0) {
					Node textNode =  nodelist.item(0).getChildNodes().item(0);
					if( textNode != null ) {
						result.put(consentItem.getParamName(), textNode.getNodeValue());
					}
				} else {
					result.put(consentItem.getParamName(), "");
				}
			}
			
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return result; 
	}
	
	@Override 
	public String toString() {
		final StringBuilder builder = new StringBuilder(FrameworkConstants.NEW_LINE); 
				
		builder.append(ConvertUtil.convertStringForDebug(this.resultMap)); 
		
		return builder.toString(); 
	}
}
