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

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

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

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.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.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.login.SessionManager;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.common.util.MonitoringSyncAgent;
import com.eactive.eai.rms.common.vo.JsonPageVo;
import com.google.gson.Gson;

@Controller
@SuppressWarnings("unchecked")
public class SpcfTmAdapterController extends OnlBaseAnnotationController{
    
	@Autowired
	@Qualifier("spcfTmAdapterService")
	private SpcfTmAdapterService service;	
	
    @Autowired
    private ComboService comboService;   
    
	@Autowired
	@Qualifier("monitoringSyncAgent")
	private MonitoringSyncAgent monitoringSyncAgent;
	
    
	@RequestMapping(value= "/onl/admin/adapter/spcfTmAdapterMan.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;
	}
	
	
	/**
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/onl/admin/adapter/spcfTmAdapterMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo, String searchAdptrBzwkGroupName,String searchAdptrMngDstCd)
			throws Exception {
		
		HashMap map = service.selectList(pageVo.getStartNum(),
				pageVo.getEndNum(), searchAdptrBzwkGroupName, searchAdptrMngDstCd);

		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/spcfTmAdapterMan.json",params = "cmd=DETAIL")
	private ModelAndView selectDetail(HttpServletRequest request,
			HttpServletResponse response,String adptrBzwkGroupName) throws Exception {
		
		HashMap map = service.selectDetail(adptrBzwkGroupName);

		ModelAndView modelAndView = new ModelAndView("jsonView",map);	
		
		return modelAndView;
	}
    
   @RequestMapping(value= "/onl/admin/adapter/spcfTmAdapterMan.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initCombo( HttpServletRequest request,
            HttpServletResponse response,String eaiSvcName) {
	    List<ComboVo> listAdapter       = comboService.getFromAdapterGroup();
        List<ComboVo> listAdptrTypes    = comboService.getFromCode("ADTR_DST_CD");
        
		Map<String, Object> resultMap = new HashMap<>();
		resultMap.put("adapterRows" , listAdapter);
		resultMap.put("adptrTypeRows" , listAdptrTypes);
		
		return new ModelAndView("jsonView",resultMap);		
    } 
   
	@RequestMapping(value= "/onl/admin/adapter/spcfTmAdapterMan.json",params = "cmd=DELETE")
	private String delete(HttpServletRequest request,
			HttpServletResponse response, @RequestParam HashMap<String,Object> map ) throws Exception {
		service.delete(map);
		syncReloadScheduler(map);
		return null;
		
	}	
   @RequestMapping(value= "/onl/admin/adapter/spcfTmAdapterMan.json",params = "cmd=INSERT")
   public ModelAndView insert( HttpServletRequest request,
           HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {
	   String userId = SessionManager.getUserId(request);
	   map.put("lastAmnuserId",userId);
	   service.insert(map);  
	   
	   String serverNm = DataSourceContextHolder.getDataSourceType().getName();
	   map.put("serverNm", serverNm);
	   syncReloadScheduler(map);
   	
   	return null;            
   }   	
   @RequestMapping(value= "/onl/admin/adapter/spcfTmAdapterMan.json",params = "cmd=UPDATE")
   public ModelAndView update( HttpServletRequest request,
           HttpServletResponse response,@RequestParam HashMap<String,Object> map) throws Exception {
	   
	   String userId = SessionManager.getUserId(request);
	   map.put("lastAmnuserId",userId);
	   
	   //사용안함 아닐경우
	   if(! "0".equals(map.get("adptrmngdstcd"))){
		   if(map.get("startYn") == null){
			   map.put("AdptrStartHms", "");
		   }else if(map.get("stopYn") == null){
			   map.put("AdptrStopHms", "");
		      
		   }
	   }
	   
	 service.update(map);  
	 
	 String serverNm = DataSourceContextHolder.getDataSourceType().getName();
	 map.put("serverNm", serverNm);
	 syncReloadScheduler(map);
   
   	return null;            
   }   
   
   // Scheduler 동기화
	public void syncReloadScheduler(Map paramMap) throws Exception{
		
		Map<String, String> ret = null;
		String JobName = "";
		List JobNames = new ArrayList();
		
		if(! "0".equals(paramMap.get("AdptrMngDstCd"))){
			if("1".equals(paramMap.get("AdptrMngDstCd"))) { //Daily 기동종료 둘다 등록
				JobName = makeJobName(paramMap,"start");
				JobNames.add(JobName);
				JobName = makeJobName(paramMap,"stop");
				JobNames.add(JobName);
			}else{
				//기동시간 있을경우
				if(!"".equals(((String) paramMap.get("AdptrStartHms")).trim())){
					JobName = makeJobName(paramMap,"start");
					JobNames.add(JobName);
				}
				if(!"".equals(((String) paramMap.get("AdptrStopHms")).trim())){ //종료시간있을경우
					JobName = makeJobName(paramMap,"stop");
					JobNames.add(JobName);
				}
			}
		}
		
		String url = "/monitoring/adapterSchedulerReload.do";
		try{
			for(int i=0; i <JobNames.size();i++){
					paramMap.put("jobName", JobNames.get(i).toString());
					ret = monitoringSyncAgent.sync(url, paramMap);
				
			}
		}
		catch(Exception e)
		{
			logger.error("syncReloadScheduler error", e);
		}
		finally{
			logger.info("Scheduler Sync Result : " + ret);
		}
	}
	
  public String makeJobName(Map<String,Object> paramMap, String startstopTxt){
    	String JobName = ""; //JobName :  어댑터그룹명 + START/STOP + 서버인스턴스명		
    	
    	JobName = (String)paramMap.get("AdptrBzwkGroupName");
    	if("start".equals(startstopTxt)){
    		JobName += "-START";
    	}else{
    		JobName += "-STOP";
    	}
		
		JobName += "-"+paramMap.get("serverNm");    	
		
		return JobName;
    }
  @RequestMapping(value= "/onl/admin/adapter/spcfTmAdapterMan.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;
  	}	

}
