package com.eactive.eai.agent.web;

import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.eactive.eai.adapter.AdapterManager;
import com.eactive.eai.batch.code.CodeMessageManager;
import com.eactive.eai.batch.eventscheduler.holiday.HolidayManager;
import com.eactive.eai.batch.flowController.FlowControllerManager;
import com.eactive.eai.batch.osd.OutsideManager;
import com.eactive.eai.batch.rule.dirInfo.DirInfoManager;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoManager;
import com.eactive.eai.batch.rule.nodeinfo.NodeInfoVO;
import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoManager;
import com.eactive.eai.batch.rule.phaseinfo.PhaseInfoVO;
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoManager;
import com.eactive.eai.batch.rule.ruleinfo.RuleInfoVO;
import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoManager;
import com.eactive.eai.batch.rule.telegraminfo.TelegramInfoVO;
import com.eactive.eai.batch.telegram.TelegramManager;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;


/**
 * LifeCycle에 의해 로드된 데이터를 원격에서 Refresh 하기 위해 제공하는 서블릿
 *
 * WebBrowser 를 통해 호출가능하도록 WEB.XML 에 URL 등록함.
 */
public class DBRefreshAgent extends HttpServlet
{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

   /**
    * 1. 기능 :  요청으로 전달된 Command 실행
    * 2. 처리 개요 : 요청으로 전달된 Command 실행하고 실행된 결과를 ObjectOutStream을 통해 전송
    * 3. 주의사항
    *
    * @param    request     HttpServletRequest
    * @param    response    HttpServletResponse
    * @return
    * @exception
    **/
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            logger.info("[DBRefreshAgent] Servlet starting .......");

            String strTarget = request.getParameter("Target");
            if (strTarget == null)  strTarget = "";

            response.setContentType("text/html;charset=euc-kr");
            if (strTarget.equalsIgnoreCase("ALL")) {
                // 일단 당분간 테스트를 위해 여기서 REFRESH 하자
                logger.info("[DBResfreshAgent] ▷▷▷ PhaseInfoManager data reload ");
                PhaseInfoManager.getInstance().stop();
                PhaseInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR02 table reloaded !!!<BR><BR>");

                logger.info("[DBResfreshAgent] ▷▷▷ NodeInfoManager data reload ");
                NodeInfoManager.getInstance().stop();
                NodeInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR03 table reloaded !!!<BR><BR>");

                logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload ");
                RuleInfoManager.getInstance().stop();
                RuleInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR04 table reloaded !!!<BR><BR>");

                logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload ");
                TelegramInfoManager.getInstance().stop();
                TelegramInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR05 table reloaded !!!<BR><BR>");

                logger.info("[DBRefreshAgentAgent] 대외기관 정보 리로딩 한다.");
                OutsideManager.getInstance().stop();
                OutsideManager.getInstance().start();
                AdapterManager.getInstance().stop();
                AdapterManager.getInstance().start();
				FlowControllerManager.getInstance().stop();
				FlowControllerManager.getInstance().start();
                response.getWriter().println("TSEAIBJ06, TSEAIBJ05 Reloading OK !!! <BR>");

                logger.info("[DBRefreshAgentAgent] 업무분류 코드 및 서브 디렉토리 정보  .");
                DirInfoManager.getInstance().stop();
                DirInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBJ01 Reloading OK !!! <BR>");

                logger.info("[DBRefreshAgentAgent] Property Table Reloading .");
                PropManager.getInstance().stop();
                PropManager.getInstance().start();
                response.getWriter().println("TSEAIBP01, TSEAIBP02 (Property table) Reloading OK !!! <BR>");

                logger.info("[DBRefreshAgentAgent] CodeMessage Table Reloading .");
                CodeMessageManager.getInstance().stop();
                CodeMessageManager.getInstance().start();
                response.getWriter().println("TSEAIBP05 CodeMessage table Reloading OK !!! <BR>");

                logger.info("[DBRefreshAgentAgent] Telegram Table Reloading .");
                TelegramManager.getInstance().stop();
                TelegramManager.getInstance().start();
                response.getWriter().println("TSEAIBM02 Telegram table Reloading OK !!! <BR>");

                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 정보 [TSEAIBR04] <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayRuleInfo(response);
                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 구성 노드 (STAGE) [TSEAIBR03] 정보<BR> ");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayNodeInfo(response);
                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 구성노드 변환 규칙  [TSEAIBR02]  <BR> ");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayPhaseInfo(response);
                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 노드(단계)별 처리 담당 클래스 리스트 [TSEAIBR05] <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayTelegramInfo(response);
                response.getWriter().println("================================================================================================<BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBR02")) {
                logger.info("[DBResfreshAgent] ▷▷▷ PhaseInfoManager data reload ");
                PhaseInfoManager.getInstance().stop();
                PhaseInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR02 table reloaded !!!<BR><BR>");

                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 구성노드 변환 규칙  <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayPhaseInfo(response);
                response.getWriter().println("================================================================================================<BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBR03")) {
                logger.info("[DBResfreshAgent] ▷▷▷ NodeInfoManager data reload ");
                NodeInfoManager.getInstance().stop();
                NodeInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR03 table reloaded !!!<BR><BR>");

                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 구성 노드 (STAGE) 정보 <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayNodeInfo(response);
                response.getWriter().println("================================================================================================<BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBR04")) {
                logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload ");
                RuleInfoManager.getInstance().stop();
                RuleInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR04 table reloaded !!!<BR><BR>");

                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 정보 <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayRuleInfo(response);
                response.getWriter().println("================================================================================================<BR>");

            }
            else if (strTarget.equalsIgnoreCase("TSEAIBR05")) {
                logger.info("[DBResfreshAgent] ▷▷▷ RuleInfoManager data reload ");
                TelegramInfoManager.getInstance().stop();
                TelegramInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBR05 table reloaded !!!<BR><BR>");

                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 노드(단계)별 처리 담당 클래스 리스트 <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayTelegramInfo(response);
                response.getWriter().println("================================================================================================<BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBJ06")) {
                logger.info("[DBRefreshAgentAgent] 대외기관 정보 리로딩 한다.");
                OutsideManager.getInstance().stop();
                OutsideManager.getInstance().start();
                AdapterManager.getInstance().stop();
                //socket이 realead되기를 기다리기 위해 2초 sleep
                Thread.sleep(2*1000);
                
                AdapterManager.getInstance().start();
				FlowControllerManager.getInstance().stop();
				FlowControllerManager.getInstance().start();
                response.getWriter().println("TSEAIBJ06, TSEAIBJ05 Reloading OK !!! <BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBJ01")) {
                logger.info("[DBRefreshAgentAgent] 업무분류 코드 및 서브 디렉토리 정보  .");
                DirInfoManager.getInstance().stop();
                DirInfoManager.getInstance().start();
                response.getWriter().println("TSEAIBJ01 Reloading OK !!! <BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBP01")) {
                logger.info("[DBRefreshAgentAgent] Property Table Reloading .");
                PropManager.getInstance().stop();
                PropManager.getInstance().start();
                response.getWriter().println("TSEAIBP01, TSEAIBP02 (Property table) Reloading OK !!! <BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBP05")) {
                logger.info("[DBRefreshAgentAgent] CodeMessage Table Reloading .");
                CodeMessageManager.getInstance().stop();
                CodeMessageManager.getInstance().start();
                response.getWriter().println("TSEAIBP05 CodeMessage table Reloading OK !!! <BR>");
            }
            else if (strTarget.equalsIgnoreCase("TSEAIBM02")) {
                logger.info("[DBRefreshAgentAgent] Telegram Table Reloading .");
                TelegramManager.getInstance().stop();
                TelegramManager.getInstance().start();
                response.getWriter().println("TSEAIBM02 Telegram table Reloading OK !!! <BR>");
            }
            else if (strTarget.equalsIgnoreCase("VIEW")) {
                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 정보 [TSEAIBR04] <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayRuleInfo(response);
                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 구성 노드 (STAGE) [TSEAIBR03] 정보<BR> ");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayNodeInfo(response);
                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 구성노드 변환 규칙  [TSEAIBR02]  <BR> ");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayPhaseInfo(response);
                response.getWriter().println("================================================================================================<BR>");
                response.getWriter().println("▷▷▷ 룰 노드(단계)별 처리 담당 클래스 리스트 [TSEAIBR05] <BR>");
                response.getWriter().println("-------------------------------------------------------------------------------------------------<BR>");
                this.displayTelegramInfo(response);
                response.getWriter().println("================================================================================================<BR>");
            }else if (strTarget.equalsIgnoreCase("TSEAIBE02")) {
            	logger.info("[DBRefreshAgentAgent] EventScheduler Holiday Table Reloading .");
                HolidayManager.getInstance().stop();
                HolidayManager.getInstance().start();
                response.getWriter().println("TSEAIBE02 EventScheduler Holiday table Reloading OK !!! <BR>");
            } else {
                logger.info("[DBResfreshAgent] ▷▷▷ unknown target !!!! >>"+strTarget+"<<<BR>");
                response.getWriter().println("Unknown Target. No process done !!! ▷▷▷ CHECK YOUR URL ▷▷▷<BR>");
                response.getWriter().println("▷▷▷ URL PATTERN ▷▷▷<BR>");
                response.getWriter().println("▷▷▷▷▷▷▷▷▷▷▷▷▷▷▷  <BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=ALL'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=ALL</A>       ▷▷▷룰관련 모든 매니저 DB 리로딩 <BR>" );
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=VIEW'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=VIEW</A>       ▷▷▷룰관련 모든 매니저 DB Display <BR>" );
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR02'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR02</A> ▷▷▷PHASE 변환룰 정보<BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR03'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR03</A> ▷▷▷PHASE 정보<BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR04'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR04</A> ▷▷▷RULE 정보<BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR05'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBR05</A> ▷▷▷텔레그램 매핑정보<BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBJ06'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBJ06</A> ▷▷▷대외기관정보 (TSEAIBJ06, TSEAIBJ05 둘다 리프레쉬)<BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBJ01'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBJ01</A> ▷▷▷파일이름기반 거래분류 테이블 <BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBP01'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBP01</A> ▷▷▷프라퍼티테이블 정보 <BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBP05'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBP05</A> ▷▷▷코드메세지 테이블 정보 <BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBM02'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBM02</A> ▷▷▷Telegram 테이블 정보 <BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBE02'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBE02</A> ▷▷▷이벤트 스케줄러 휴일관리  테이블 정보 <BR>");
                response.getWriter().println("<A href='http://" + request.getServerName()+":"+request.getServerPort()+ request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBE03'>http://" + request.getServerName()+":"+request.getServerPort()+ "/" + request.getContextPath() + "/DBRefreshAgent?Target=TSEAIBE03</A> ▷▷▷이벤트 스케줄러  테이블 정보 <BR>");
            }
        } catch (Exception ex) {
        	logger.error( ex.getMessage(), ex);
            response.setStatus(500);
            try {
                response.getWriter().println(ex.getMessage());
                throw ex;
            } catch (Exception e) {
                // IGNORE
            }
        }
    }

    public void displayPhaseInfo(HttpServletResponse response) {
        try {
        	HashMap<String, ArrayList<PhaseInfoVO>> hm = PhaseInfoManager.getInstance().getAllData();
            Object[] objs = hm.keySet().toArray();
            for (int i=0; i<objs.length; i++) {
                String rulecode = (String)objs[i];
                ArrayList<PhaseInfoVO> al = hm.get(rulecode);
                response.getWriter().println("RULE ["+rulecode+"] phase(stage) change rule record count  >> " + al.size() + "<BR>");
            }
        } catch(Exception ex) {
        }
    }

    public void displayNodeInfo(HttpServletResponse response) {
        try {
        	HashMap<String, ArrayList<NodeInfoVO>> hm = NodeInfoManager.getInstance().getAllData();
            Object[] objs = hm.keySet().toArray();
            for (int i=0; i<objs.length; i++) {
                String rulecode = (String)objs[i];
                ArrayList<NodeInfoVO> al = hm.get(rulecode);
                response.getWriter().println("RULE ["+rulecode+"] distinct node(stage) count  >> " + al.size()+ "<BR>");
            }
        } catch(Exception ex) {
        }
    }

    public void displayRuleInfo(HttpServletResponse response) {
        try {
        	HashMap<String, RuleInfoVO> hm = RuleInfoManager.getInstance().getAllData();
            Object[] objs = hm.keySet().toArray();
            for (int i=0; i<objs.length; i++) {
                String rulecode = (String)objs[i];
                RuleInfoVO  vo = hm.get(rulecode);
                response.getWriter().println("RULE ["+rulecode+"] >>> " + vo.getDesc()+ "<BR>");
            }
        } catch(Exception ex) {
        }
    }

    public void displayTelegramInfo(HttpServletResponse response) {
        try {
        	HashMap<String, TelegramInfoVO> hm = TelegramInfoManager.getInstance().getAllData();
            Object[] objs = hm.keySet().toArray();
            for (int i=0; i<objs.length; i++) {
                String telegramid = (String)objs[i];
                TelegramInfoVO  vo = hm.get(telegramid);
                response.getWriter().println("TELEGRAM MAPPING ["+telegramid+"] : Telegram MetaCode ["+vo.getMsgMetaDstcd()+"] --- Class ["+vo.getTelegramClsName()+"]<BR>");
            }
        } catch(Exception ex) {
        }
    }

}
