package com.eactive.eai.rms.onl.adapter.socket;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.data.entity.onl.server.EAIServer;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.eactive.eai.rms.data.entity.onl.server.EAIServerService;
import com.eactive.eai.rms.onl.adapter.common.vo.ErrorContentForm;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.common.util.CallAgentUtil;
import com.eactive.eai.rms.onl.common.vo.HostInfomationForm;
import com.google.gson.Gson;

/**
 * <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 SocketLogContentsController 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
    private MonitoringContext monitoringContext;
    

    @Autowired
    private ComboService comboService;
    
    @Autowired
    private EAIServerService eaiServerService;

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


	@RequestMapping(value= "/onl/adapter/socket/socketLogContents.view")
	private String viewList(HttpServletRequest request, @RequestParam(value = "cmd", required = false ) String cmd ) throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())){
			cmd = "";
		}else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0]+cmd;
	}   
	
	@RequestMapping(value = "/onl/adapter/socket/socketLogContents.json", params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo(HttpServletRequest request, HttpServletResponse response) {

		List<ComboVo> instanceList = comboService.getFromEAIServerWithoutAll();
		List<ComboVo> loglevelList = comboService.getFromCode("SNA_SEARCH_LOGLEVEL");

		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("instanceList", instanceList);
		resultMap.put("logLevelRows", loglevelList);

		return new ModelAndView("jsonView", resultMap);
	}

	
	@RequestMapping(value= "/onl/adapter/socket/socketLogContents.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,String searchEaiSevrInstncName , String searchLogLevel, String searchText) throws Exception {
		
		EAIServer selectedServer = eaiServerService.getByEaiSevrInstncName(searchEaiSevrInstncName);

		//LOG 파일 위치 프라퍼티로 
        String defaultLogPath = monitoringContext.getStringProperty(
                MonitoringContext.DEFAULT_LOG_PATH, "/fslog/eai/");
        String socketLogFile = monitoringContext.getStringProperty(
            MonitoringContext.SOCKET_LOG_FILE, "netAdapter.log");
        String logPath = "";
        
        logger.info("defaultLogPath : "+defaultLogPath);
        
        if (defaultLogPath == null || defaultLogPath.equals("")) {
            logPath = "/fslog/eai/" + searchEaiSevrInstncName + socketLogFile;
        } else {
            logPath = defaultLogPath + searchEaiSevrInstncName + "/"
                    + socketLogFile;
        }
        logger.info("logPath : "+logPath);
		
        //http://192.168.68.21:30311/ONLWeb/agent/host/adapter_log_agent.jsp?logLevel=TOTAL&fileName=/fslog/eai/EAIDS01_i01/netAdapter.log
        //searchText=[찾으려는값]
        //checkHead=[라인의 시작문자]
        //skipLineCount=[이전페이지의 마지막 라인수]
		String url = "http://" + (String) selectedServer.getEaisevrip() + ":"
					+ (String) selectedServer.getSevrlsnportname()
					+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH
					+ AGENT_PAGE
					+ "?logLevel=" + searchLogLevel
					+ "&fileName=" + logPath
					+ "&searchText=" + URLEncoder.encode(searchText)
					;
		logger.info("url : "+url);
		
		CallAgentUtil util = new CallAgentUtil();
		List<HashMap<String, Object>> list = new ArrayList<>();
		HashMap map = null;
		String result = util.getAgentDataToString(url);
		
		int linePoint = 0;

	    // 정보를 라인단위로 파싱하여
		if(result != null){
			linePoint = result.indexOf("\n");
		}
	    
	    while (linePoint > -1) {
	      map = new HashMap();
	      // 한 라인만을 읽어 온다.
    	  String line = null;
    	  if(result != null){
    		  line = result.substring(0, linePoint);
    	  }
    	  
          result = result.substring(linePoint + 1);
          map.put("logContent", line);
          list.add(map);           
          
          linePoint = result.indexOf("\n");
	    }
		
		Map resultMap = new HashMap();
		resultMap.put("total"  , pageVo.getTotal());  //전체 페이지수
		resultMap.put("page"   , pageVo.getPage());   //현재 페이지수
		resultMap.put("records", pageVo.getTotalCount());//전체 레코드건수	
		resultMap.put("rows"   , list);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
		
	}	
    
    
    /**
     * <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("/onl/adapter/socket/socketLogContents.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) 로그 데이터를 역순으로 출력한다.
//            if(arrResult != null){ //취약점소스 수정 2020.08.24
//        	  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;
//        }
    }
    
	
    @RequestMapping(value= "/onl/adapter/socket/logInfoMation.view")
	private String viewLogInfoMation(HttpServletRequest request, @RequestParam(value = "cmd", required = false ) String cmd ) throws Exception {
		if (cmd == null || "LIST".equals(cmd.toUpperCase())){
			cmd = "";
		}else {
			cmd = CamelCaseUtil.converCamelCase(cmd);
		}
		String path = request.getServletPath();
		return path.split("[.]")[0]+cmd;
	}   
    
	@RequestMapping(value= "/onl/adapter/socket/socketLogContents.excel",params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		
		HashMap<String,Object> resultMap = new HashMap<String,Object>();
		Gson gson = new Gson();
    	String jsonStr = (String)paramMap.get("gridData");
    	HashMap<String, Object>[] dataList = gson.fromJson(jsonStr, HashMap[].class);
    	
		String[] headers = gson.fromJson((String) paramMap.get("header"), String[].class);
		String[] headerTitles = gson.fromJson((String)paramMap.get("headerTitle"), String[].class);
		
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", dataList);
    	resultMap.put("fileName", (String)paramMap.get("fileName"));
		ModelAndView modelAndView = new ModelAndView("excelView",resultMap);	
        return modelAndView;
    }	

}
