package com.eactive.eai.rms.common.util;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class MessengerPlusSender {
	protected final static Logger logger = Logger.getLogger(MessengerPlusSender.class);

	private static MessengerPlusSender instance ;
	
    private HttpClient client;
    
    // HttpClient 2.0 Timeout Setting
    public static final int   DEFAULT_TIME_OUT = 30 *1000;
    // HttpClient 2.0 Timeout Setting 
    
	public static MessengerPlusSender getInstance() {
		if (instance == null){
			synchronized (MessengerPlusSender.class) {
				if (instance == null){
					instance = new MessengerPlusSender();
				}
			}
		}
		return instance;
	}
    
    private MessengerPlusSender() {
        MultiThreadedHttpConnectionManager cm ;
        try {     
        	cm = new MultiThreadedHttpConnectionManager();
			cm.getParams().setStaleCheckingEnabled(new Boolean(true).booleanValue());	
			cm.getParams().setDefaultMaxConnectionsPerHost(new Integer(5).intValue());
			cm.getParams().setMaxTotalConnections(new Integer(10).intValue());
        } catch(Exception e) {
        	logger.error(e.toString() ,e);
            throw e;
        }
        this.client = new HttpClient(cm);
    }
    
    /** 
    * 1. 기능 :  전문과 같은 Raw Data 통신에 사용
    * 2. 처리 개요 : 
    *     - 속성 정보를 설정 하고 수동 시스템 서비스를 호출 한다.
    * 3. 주의사항 
    *
    * @param    prop    Http Adapter 속성 정보
    * @param    message 송신 전문
    * @return   반환 된 byte[] Object
    * @exception    Exception 수동 시스템 간 통신 중 발생
    **/
    public void execute(String url, String srvCode, String recipient, String send, String title, String body, String saveOption, String senderAlias) throws Exception
    {
        PostMethod method = new PostMethod(url);

        method.getParams().setSoTimeout(DEFAULT_TIME_OUT);
        
        HttpClient mclient = this.client;
        mclient.getParams().setContentCharset("utf-8");
        method.addParameter("SRV_CODE",srvCode);
        method.addParameter("RECIPIENT",recipient);
        method.addParameter("SEND",send);
        method.addParameter("TITLE",title);
        method.addParameter("BODY",body);
        if (!StringUtils.isEmpty(saveOption)){
        	method.addParameter("SAVEOPTION",saveOption);
        }
        if (!StringUtils.isEmpty(senderAlias)){
        	method.addParameter("SENDER_ALIAS",senderAlias);
        }
        int status =0;
        try{
        
	        status = mclient.executeMethod(method);
	        
	        //status 200(정상) 이외에는 error 처리 
	        if (status !=200){
	        	throw new Exception ("http receive status fail value= " + status);
	        }
            String responseMessage = new String(method.getResponseBody());
            logger.debug("response Message : " + responseMessage);
            //System.out.print(responseMessage);
        } catch(SocketTimeoutException ste) { // Read Timeout :: HttpClient 3.1일 경우
            logger.error("MessengerPlusSender] SocketTimeoutException : " + ste.toString() ,ste);
            throw ste;
        } catch(ConnectException ce) {
            logger.error("MessengerPlusSender] Connection Exception : " + ce.toString() ,ce);
            throw ce;
        } catch(Exception e) {
            logger.error("MessengerPlusSender] Exception : " + e.toString() ,e);
            throw e;
        } finally {
            method.releaseConnection();
        }
    }
    
//    public static void main (String[] args){ //취약점소스 수정 2020.08.26
//        MessengerPlusSender sender = MessengerPlusSender.getInstance();
//        //String url       = "http://172.17.31.103:8081/HMemoService";//stage
//        String url     = "http://172.17.179.45/HMemoService";//운영
//        //String srvCode   = "EAID02";//stage
//        String srvCode   = "EAI002";
//        String recipient = "S010794";
//        String send      = "S010794";
//        String title     = "EAI 라우팅추출정보 등록요청";
//        StringBuffer sb = new StringBuffer();
//		sb.append("EAI서비스코드   : " + "AAA0000BBBS01" ).append("<br>");
//    	sb.append("라우팅 추출 정보 관리에 서비스코드("+"AAA0000BBBS01"+")가 미등록 상태입니다" ).append("<br>");
//        try {
//                sender.execute(url, srvCode, recipient, send, title, sb.toString(), "", "EAI시스템");
//                } catch (Exception e) {
//                	//취약점소스 수정 2020.08.24
//                	logger.error("error ",e); 
//                    //e.printStackTrace();
//                }
//    	}
}