package kccf.sch.service.impl;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import egovframework.rte.fdl.cmmn.EgovAbstractServiceImpl;
import  kccf.sch.service.ArkService;
import  kccf.sch.service.vo.ArkVO;
import  kccf.sch.service.vo.Sf1VO;

@Service("ArkService")
public class ArkServiceImpl extends  EgovAbstractServiceImpl implements ArkService{
	private static final Logger LOGGER = LoggerFactory.getLogger(ArkServiceImpl.class);
	
	/**
	 *  자동완성 호출
	 */
	@Override
	public String getArk(ArkVO arkVo, Sf1VO sf1Vo) throws Exception {
		StringBuffer urlSb = new StringBuffer();		
		urlSb.append("http://");
		urlSb.append(sf1Vo.getManagerIp()).append(":");
		urlSb.append(sf1Vo.getManagerPort());
		urlSb.append("/manager/WNRun.do?");
		
		urlSb.append("target=").append(arkVo.getTarget());
		urlSb.append("&query=").append(URLEncoder.encode(arkVo.getQuery(), "UTF-8")); 
		urlSb.append("&convert=").append(arkVo.getConvert());
		/*urlSb.append("&eq=").append(arkVo.getCharset());
		urlSb.append("&es=").append(arkVo.getCharset());*/
		
		String url = urlSb.toString();
		if(arkVo.getDebugType().equals("Y")){
			LOGGER.info("[getArk() URL]["+url+"]");
			LOGGER.info("[getArk() sf1Vo.toString()]["+sf1Vo.toString()+"]");
			LOGGER.info("[getArk() arkVo.toString()]["+arkVo.toString()+"]");
		}
		return getHtmls(url, arkVo.getTimeOut() , arkVo.getDataType(), arkVo.getCharset());
	}
	
	/**
	 * 관리도구 자동완성 URL 호출해야 해당 결과 담기
	 * @param receiverURL 관리도구 URL 정보
	 * @param parameter ark 파라미터값
	 * @param timeout ark 연결 시간 고정으로 1000 
	 * @param datatype 관리도구 web화면 데이타 타입
	 * @param charset 케릭터 타임
	 * @return dataType 에 따른 자동완성 결과
	 */
	private String getHtmls(String receiverURL, int timeout, String datatype , String charset) {
		StringBuffer receiveMsg = new StringBuffer();
		BufferedReader in = null;
		int errorCode = 0;
		try {
			
			// -- receive servlet connect
			URL servletUrl = new URL(receiverURL);
			HttpURLConnection uc = (HttpURLConnection)servletUrl.openConnection();
			uc.setReadTimeout(timeout);
			uc.setRequestMethod("GET");
			uc.setDoOutput(true);
			uc.setDoInput(true);
			uc.setUseCaches(false);
			uc.connect();
			// init
            errorCode = 0;
            //System.out.println("[URLConnection Response Code] " + uc.getResponseCode());
			// -- Network error check
			if (uc.getResponseCode() == HttpURLConnection.HTTP_OK) {
				String currLine = new String();
				//UTF-8인 경우
                in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
                while ((currLine = in.readLine()) != null) {
                	receiveMsg.append(currLine).append("\r\n");
                }
            } else {
                  errorCode = uc.getResponseCode();
                  return receiveMsg.toString();
            }
			uc.disconnect();
       } catch(Exception ex) {
    	   receiveMsg.setLength(0);
    	   if(datatype.toLowerCase().equals("xml")){
    		   receiveMsg.append("<?xml version=\"1.0\" encoding=\""+charset+"\" ?>");
    		   receiveMsg.append("<Response>");
    		   receiveMsg.append("<Value>");
    		   receiveMsg.append("<Return>0</Return>");
    		   receiveMsg.append(" <ARKList>");
    		   receiveMsg.append("<TotalCount>0</TotalCount>");
    		   receiveMsg.append("</ARKList>");
    		   receiveMsg.append("<ARKRList>");
    		   receiveMsg.append(" <TotalCount>0</TotalCount>");
    		   receiveMsg.append("</ARKRList>");
    		   receiveMsg.append("</Value>");
    		   receiveMsg.append("</Response>");
    	   }else if(datatype.toLowerCase().equals("json")){
    		   receiveMsg.append("{\"responsestatus\":0,\"result\":[{\"totalcount\":0},{\"totalcount\":0}]}");
    	   }
    	   LOGGER.debug("[getHtmls() URL]["+ receiverURL +"]");
    	   LOGGER.debug("[getHtmls() error][errorCode:"+errorCode+"]["+ex+"]");
       } finally {
            if (in != null) {
                try {
                	in.close();
                } catch (IOException ex) {
                	LOGGER.info("IOException occurred");
                }
            }
       }
       return receiveMsg.toString();
	}

	
}
