package com.eactive.eai.rms.onl.manage.adapter.sna;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.eactive.eai.adapter.wca.cfg.WcaInfoDataEx;
import com.eactive.eai.adapter.wca.command.UpdateWcaAppCodeEx;
import com.eactive.eai.agent.command.Command;
import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.combo.ComboService;
import com.eactive.eai.rms.common.combo.ComboVo;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.manage.adapter.adapter.AdapterManService;
import com.eactive.eai.rms.onl.manage.adapter.adapter.ui.AdapterGroupUI;
import com.eactive.eai.rms.onl.manage.comm.server.EAIServerUI;
import com.eactive.eai.rms.onl.manage.comm.server.ServerManService;
import com.google.gson.Gson;

@Controller
public class SnaAdapterController extends OnlBaseAnnotationController {
	
	private static final Logger logger = Logger.getLogger(SnaAdapterController.class);

	@Autowired
	@Qualifier("snaAdapterService")
	private SnaAdapterService service;	
	
	@Autowired
	private AdapterManService adapterManService;
	
    @Autowired
    private ComboService comboService; 

	@Autowired
	private ServerManService serverManService;
	
	@RequestMapping(value= "/onl/admin/adapter/snaAdapterMan.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;
	}
	
	@PostMapping(value= "/onl/admin/adapter/snaAdapterMan.json",params = "cmd=LIST_INIT_COMBO")
    public ResponseEntity<Map<String, Object>> searchInitCombo() {

		List<ComboVo> listUseYn    = comboService.getFromCode("USE_YN");
		List<ComboVo> listInstance = comboService.getFromEAIServer();
		 
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("useYnRows", listUseYn);
		resultMap.put("instanceRows" , listInstance);
		
		return ResponseEntity.ok(resultMap);            
    }
	
	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/onl/admin/adapter/snaAdapterMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo,@RequestParam HashMap<String,Object> paramMap)throws Exception {

		HashMap map = service.selectList(pageVo.getStartNum(),pageVo.getEndNum(), paramMap);

		pageVo.setTotalCount((Integer) map.get("totalCount"));

		Map resultMap = new HashMap();
		resultMap.put("total", pageVo.getTotal()); // 전체 페이지수
		resultMap.put("page", pageVo.getPage()); // 현재 페이지수
		resultMap.put("records", pageVo.getTotalCount());// 전체 레코드건수
		resultMap.put("rows", map.get("list"));

		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;

	}
	
	@RequestMapping(value= "/onl/admin/adapter/snaAdapterMan.json",params = "cmd=DETAIL")
	private ResponseEntity<AdapterGroupUI> selectDetail(HttpServletRequest request,
			HttpServletResponse response,String ADPTRBZWKGROUPNAME) throws Exception {
		
		throw new BizException("jpa 적용 후 테스트 되지 않음. jsp에 수정 사항 있음");
//		AdapterGroupUI adapterGroupUI = adapterManService.selectDetail(ADPTRBZWKGROUPNAME);
//		return ResponseEntity.ok(adapterGroupUI);
	}
	
	@RequestMapping(value= "/onl/admin/adapter/snaAdapterMan.json",params = "cmd=DETAIL2")
	private ModelAndView selectAppCodeDetail(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> paramMap) throws Exception {

		HashMap map = service.selectAppCode(paramMap);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",map);	
		
		return modelAndView;
	}	
	
	@RequestMapping(value= "/onl/admin/adapter/snaAdapterMan.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>();
		
		String headersStr = (String) paramMap.get("headersStr"); 
		headersStr = headersStr.substring(0, headersStr.length()-1);
		paramMap.put("headersStr", headersStr);
		
    	Gson gson = new Gson();
    	@SuppressWarnings("unchecked")
    	HashMap<String, Object> list = service.selectListToExcel(paramMap);
    	
    	String jsonStr = gson.toJson(list.get("list"));
    	HashMap<String, Object>[] list2 = 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);
		
		HashMap<String, Object>[] lmerge = null; 
		String merge = (String)paramMap.get("merge");
		if (merge !=null){
			lmerge = gson.fromJson(merge, HashMap[].class);
		}
    	
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", list2);
    	resultMap.put("fileName", (String)paramMap.get("fileName"));
    	resultMap.put("merge", lmerge);
		ModelAndView modelAndView = new ModelAndView("excelView",resultMap);	
        return modelAndView;
    }	
	
	@RequestMapping(value = "/onl/admin/adapter/snaAdapterMan.json", params = "cmd=LIST_ADAPTER_BIZ")
	public ModelAndView selectListBiz(HttpServletRequest request,
			HttpServletResponse response,@RequestParam HashMap<String,Object> paramMap) throws Exception {
		//SNA 어댑터 APP_CODE 프라퍼티 MAP 담기
		String[] tmpCd = null;  //SNA업무코드
		String cd = "";
		List<Map<String, String>> dbMapList = adapterManService.selectAdapterPropInfo(paramMap);
		HashMap<String,String> appCdMap = null;
		
		if(dbMapList.size() > 0 && dbMapList != null){
			for(Map<String, String> tmp : dbMapList){
				cd = tmp.get("PRPTY2VAL");
			}
			tmpCd = cd.split(",");
			appCdMap = new HashMap<String,String>();
			for(String code : tmpCd ){
				appCdMap.put(code, code);
			}
		}
		
		String searchBzwkName = (String)paramMap.get("searchBzwkName");
		paramMap.put("searchBzwkName", "Y".equals((String)paramMap.get("searchBzwkName")) ? "" : searchBzwkName);
		
		//CM01 업무코드
		List<HashMap<String, Object>> list  =  service.selectAdapterBizList(paramMap);
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>(); 
		
		if("Y".equals((String)paramMap.get("targetGridYn")))
		{
			for(HashMap<String, Object> bizTmp : list){
				if(appCdMap != null){
					String code = (String)bizTmp.get("BIZCODE");
					String appCode = (String)appCdMap.get(code.trim());
					
					if(code.trim().equals(appCode)){
						bizTmp.put("CHK", "true");
						resultList.add(bizTmp);
					}
				}
			}
		}
		else
		{
			for(HashMap<String, Object> bizTmp : list){
				if(appCdMap != null){
					String code = (String)bizTmp.get("BIZCODE");
					String appCode = (String)appCdMap.get(code.trim());
					
					if(! code.trim().equals(appCode)){
						bizTmp.put("CHK", "false");
						resultList.add(bizTmp);
					}
				}else{
					bizTmp.put("CHK", "false");
					resultList.add(bizTmp);
				}
				
			}
			
			
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("rows", resultList);
		ModelAndView modelAndView = new ModelAndView("jsonView", map);
		return modelAndView;
	}
	
	
	@RequestMapping(value = "/onl/admin/adapter/snaAdapterMan.json", params = "cmd=UPDATE_ADAPTER_BIZ")
	public ModelAndView updateListBiz(HttpServletRequest request,
			HttpServletResponse response,String gridData ,String prptygroupName, String adptrbzwkgroupname , String eaiSevrInstncName) throws Exception {
		
		HashMap<String,Object> paramMap = new HashMap<String,Object>();
		
		String message = "";
		
		//화면에서 받은 체크된 biz code
		paramMap.put("ADPTRBZWKGROUPNAME", adptrbzwkgroupname);
		paramMap.put("PRPTYGROUPNAME", prptygroupName);
		paramMap.put("PRPTYNAME","APP_CODE");
		paramMap.put("EAISEVRINSTNCNAME", eaiSevrInstncName);
		
		//코드 정렬
		String appCode = "";
		String[] temp = null; //취약점소스 수정 2020.08.24
		if(gridData != null){
			temp = gridData.split(",");
		}
		
		Arrays.sort(temp);
		
		if(temp != null){//취약점소스 수정 2020.08.26
			for(int i=0;i<temp.length;i++){
				appCode += ("".equals(appCode)?"":",")+temp[i];
			}
		}
		paramMap.put("PRPTY2VAL", appCode);
		
		logger.info("DB UPDATE paramMap : " + paramMap.toString());
		service.updateOrDeleteAdapterProperty(paramMap);
		
		//서버 노드명 
		EAIServerUI map = serverManService.selectDetail(eaiSevrInstncName);
		String hostname = map.getHostName();
		
		//command 
		WcaInfoDataEx data = new WcaInfoDataEx(adptrbzwkgroupname, prptygroupName,hostname ,eaiSevrInstncName ,appCode);
		
		logger.info("WcaInfoDataEx data : " + data.toString());
		
		message = updateWcaAppCodeApply(data);
		
		logger.info("updateWcaAppCodeApply message : " + message);
		
		Map resultMap = new HashMap();
		resultMap.put("message"   , message);
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}
	
	private String updateWcaAppCodeApply(WcaInfoDataEx data) throws Exception
	{
		HashMap result = new HashMap();
		String msg = "success";
		Command command = null;
		try {
			command = new UpdateWcaAppCodeEx();
			command.setArgs(data);
			agentUtilService.broadcast(command,data.sEaiInstanceName);
		}
		catch (Exception e) {
			//e.printStackTrace();
			msg = "시스템 적용 실패하였습니다. "  ;
		}
		
		if (result.size() > 0){ // 에러가 있을 경우
			msg = "시스템 적용 실패하였습니다.   <Br> " + makeErrorString(result);
			throw new Exception(msg);
		}
		
		return msg;
	}
	
	  private String makeErrorString(HashMap result)
	    {
	        StringBuffer sbResult = new StringBuffer();
	        Iterator it = result.keySet().iterator();
	        String sSvrName = null;
	        String sResult = null;
	        while(it.hasNext()) {
	            sSvrName = (String)it.next();    
	            sResult  = (String)result.get(sSvrName);
	            if (sResult.equals("success")) continue;            
	            sbResult.append(sSvrName + " : " + sResult +"<br>");
	        }
	        return sbResult.toString();
	    }
	

}
