package com.eactive.eai.rms.onl.adapter.socket2.controller;

import java.io.IOException;

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

import org.apache.commons.httpclient.NameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.onl.adapter.common.vo.ErrorContentForm;


/**
 * <pre>
 * 1. 기능 : SOCKET 로그 정보
 * 2. 처리 개요 : 
 *     - 
 * 3. 주의사항 :
 * Xml을 수신하지 않고 String을 받아 처리한다.(CallAgentUtil 이용) 
 * 이전 로컬 WAS에서 Service단에서 Agent없이 조회하던 방식
 * 방식 변경(2008/05/21) --> Agent
 * Agent(2008/04까지) --> Local WAS(2008/04 이후) --> Agent(2008/05/21이후)
 * 
 * </pre>
 * 
 * @author : vs.net
 * @version : $Revision: 1.5 $
 * @since : rts 1.0
 */
@Controller
public class SocketLogContents2Controller extends BaseController  {
    // private final String AGENT_PAGE = "/adapter/socket/adapter_socket_log_content_agent.jsp";
    private final String AGENT_PAGE = "adapter_log_agent.jsp";

    @Autowired
    @Qualifier("monitoringContext")
    private transient MonitoringContext monitoringContext;

    /*
     *	/adapter/socket/adapter_socket_log_content.jsp
     *	/adapter/socket/adapter_socket_log_content_data.jsp
     *	/adapter/socket/adapter_socket_log_content_agent.jsp
     */

    /**
     * <pre>
     * 1. 기능 : SOCKET 로그 정보
     * 2. 처리 개요 : 
     *     - 
     * 3. 주의사항 : Overriden 
     * </pre>
     * 
     * @author : vs.net
     * @version : $Revision: 1.5 $
     * @since : rts 1.0
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/adapter/socket2/socketLogContents2.do")
    public ModelAndView handleRequest(HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //Map model = this.createModel(request);
        ErrorContentForm form = new ErrorContentForm();

        // parameter 설정
        form.setEaiSvrInstNm(request.getParameter("eaiSvrInstNm"));
        form.setEaiSvrIp(request.getParameter("eaiSvrIp"));
        form.setEaiSvrLsnPort(request.getParameter("eaiSvrLsnPort"));
        form.setAgentPage(AGENT_PAGE);
        form.setSearchText(request.getParameter("searchText"));
        form.setLogLevel(request.getParameter("logLevel"));

        String cmd = request.getParameter("cmd");

//        try {
//            // adapter.socket2.findLogContentsAgent
//            if ("SELECT_LIST".equals(cmd)) {
//                getLogList(request, response, form);
//            }
//        } catch (BizException be) {
//            //be.printStackTrace();
//            logger.error("[BIZ ERROR]");
//            ((HttpGauceResponse) response).addException(be);
//        } catch (SysException se) {
//            //se.printStackTrace();
//            logger.error("[SYS ERROR]");
//            ((HttpGauceResponse) response).addException(se);
//        } catch (Exception e) {
//            //e.printStackTrace();
//            logger.error("[SYS ERROR]");
//            ((HttpGauceResponse) response).addException(e);
//        } finally {
//            GauceOutputStream gos = null;
//            gos = ((HttpGauceResponse) response).getGauceOutputStream();
//
//            if (gos != null) {
//                try {
//                    gos.close();
//                } catch (Exception e) {
//                    gos = null;
//                }
//            }
//        }

        return null;
    }

    /**
     * <pre>
     * 1. 기능 : 로그 리스트 조회
     * 2. 처리 개요 :
     *     -
     * 3. 주의사항 :
     * </pre>
     * 
     * @author : vs.net
     * @version : $Revision: 1.5 $
     * @since : rts 2.0
     * @param request
     * @param response
     * @param form
     * @throws ServletException
     * @throws IOException
     */
    private void getLogList(HttpServletRequest request,
            HttpServletResponse response, ErrorContentForm form)
            throws Exception {
        String url = form.getWebAgentPath();

        // YUN_DEBUG (2008.05.22)
        // local 에서 테스트 하기 위해 default 값을 사용함
        String defaultLogPath = monitoringContext.getStringProperty(
            MonitoringContext.DEFAULT_LOG_PATH, "/fslog/eai/");
        String socketLogFile = monitoringContext.getStringProperty(
            MonitoringContext.SOCKET_LOG_FILE, "netAdapter.log");
        String logPath = "";
        if (defaultLogPath == null || defaultLogPath.equals("")) {
            logPath = "/fslog/eai/" + form.getEaiSvrInstNm() + socketLogFile;
        } else {
            logPath = defaultLogPath + form.getEaiSvrInstNm() + "/"
                    + socketLogFile;
        }

        // 파라미터에 특수문자가 포함되어 있으므로 Post 방식으로 WebMethod를 실행해야 한다.
        NameValuePair[] postParameters = new NameValuePair[] {
                new NameValuePair("fileName", logPath),
                new NameValuePair("logLevel", form.getLogLevel()),
                new NameValuePair("searchText", form.getSearchText()) };

        // debug
        logger.debug("SocketLogContentsController:getLogList()");
        logger.debug("url=" + url);
        for (int i = 0; i < postParameters.length; i++) {
            logger.debug("param:" + postParameters[i].getName() + " : ["
                    + postParameters[i].getValue() + "]");
        }

//        GauceInputStream gis = null;
//        GauceOutputStream gos = null;
//
//        try {
//            gis = ((HttpGauceRequest) request).getGauceInputStream();
//            gos = ((HttpGauceResponse) response).getGauceOutputStream();
//            GauceDataSet dataSet = gis.read("ds_01");
//
//            // Agent를 호출한다.
//            CallAgentUtil util = new CallAgentUtil();
//            String result = util.getAgentDataToString(url, postParameters);
//            String arrResult[] = null;
//            if(result != null){
//            	 arrResult= result.split("\n");
//            	 // YUN_DEBUG : (2008.05.22) 로그 데이터를 역순으로 출력한다.
//                 for (int i = arrResult.length - 1; i >= 0; i--) {
//                     dataSet.put("sline", arrResult[i], 1000,
//                         GauceDataColumn.TB_NORMAL);
//                     dataSet.heap();
//                 }
//            }
//
//            gos.write(dataSet);
//        } catch (Exception e) {
//            throw e;
//        }
    }

}
