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

import java.io.IOException;
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.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.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.common.exception.EMSRuntimeException;
import com.eactive.eai.rms.onl.manage.sna.lugroup.LuGroupService;
import com.google.gson.Gson;

@Controller
public class SnaProcessStatusController extends BaseController{
	
	
	@Autowired
	@Qualifier("snaProcessStatusService")
	private SnaProcessStatusService service; 
	
	@Autowired
	@Qualifier("luGroupService")
	private LuGroupService groupService; 
	
	@Autowired
	private EAIServerService eaiServerService;
	
	private final String CMD_STATUS		= "SnaStatus -t -host ";
	private final String CMD_INIT			= "SnaRestat -a -host ";
	private final String CMD_START			= "BackupLUStart -t -host ";
	private final String CMD_STOP			= "BackupLUStop -t -host ";
	
	@Autowired
	@Qualifier("comboService")
	private ComboService comboService; 
	
	@RequestMapping(value= "/onl/adapter/sna/snaProcessStatusMan.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/sna/snaProcessStatusMan.json",params = "cmd=LIST_INIT_COMBO")
	public ModelAndView initCombo( HttpServletRequest request,HttpServletResponse response) throws Exception {
	   
//	   List snaHostList = comboService.selectListComboForTable("TSEAIAD13", "SNAADPTRSEVRNAME","SNAADPTRSEVRIPNAME", "", "SNAADPTRSEVRNAME");
	  
	   Map resultMap = new HashMap();
//       resultMap.put("snaHostRows" , snaHostList);
			
	   ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
	   return modelAndView;            
	} 
	
	@RequestMapping(value= "/onl/adapter/sna/snaProcessStatusMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String,Object> paramMap) throws Exception {

		List snaHostList = groupService.selectSnaHostList(paramMap);
		
		// YUN_info
		if( logger.isInfoEnabled()) {
	        logger.info("findStatusNonAgent snaHostList=" + snaHostList);		    
		}
		
		String[] url = new String[snaHostList.size()];
		
		//String adptGrpNm = "";
		//String luGrpNm = "";
		String snaStatusCmd = "";
		List<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
		
		try
		{

			logger.info("########## START findStatusNonAgent ##########");

			// 호출할 Agent Page List
			for (int i = 0; i < url.length ; i++)
			{
				logger.info("########## start for : " + i + " ###");

				Map serverMap = (Map) snaHostList.get(i);
				snaStatusCmd = (CMD_STATUS + (String) serverMap.get("EAISVRIP"));
				//form.setSnaStatusCmd(CMD_STATUS + "172.17.50.51");
				
				// YUN_info
				if( logger.isInfoEnabled()) logger.info("YUN_info command : [" + CMD_STATUS + (String) serverMap.get("EAISVRIP") + "]");
				if( logger.isInfoEnabled()) logger.info("########## init service ##########");

				if( logger.isInfoEnabled()) logger.info("########## call service ##########");
				List list = service.executeSnaStatus(snaStatusCmd);
				
				// YUN_info
				if( logger.isInfoEnabled()) logger.info("returned list size = " + list.size() );
				
				String hostName = (String) serverMap.get("HOSTNAME");
				//String hostName = "keaita02";
				
				HashMap<String, Object> rsMap = new HashMap<String, Object>();
				
				if( logger.isInfoEnabled()) logger.info("########## start result loop ##########");
				// 호출 결과가 없으면 서버명만 출력한다.
				// 예전 AS-IS에 process_status_data.jsp에서 처리하던 것
				if (list.size() < 1)
				{
					if( logger.isInfoEnabled()) logger.info("########## no data ##########");
					rsMap.put("hostNm",hostName);
					rsMap.put("taskCode","");
					rsMap.put("luGroup","");
					rsMap.put("luGroupState","");
					rsMap.put("numLu", "");
					rsMap.put("backupLu","");
					rsMap.put("upLu", 	"");
					rsMap.put("usefulLu","");
					rsMap.put("resLu", "");
					rsMap.put("sendLu","");
					rsMap.put("wcaSession","");
					rsMap.put("sendCnt", "");
					rsMap.put("resCnt","");
					rsMap.put("timeOut", "");
					rsMap.put("sendFailCnt","");
					rsMap.put("resFailCnt","");
					rsMap.put("queueWaitCnt","");
					rsMap.put("queueWaitMaxCnt","");
					
					resultList.add(rsMap);
				}
				else
				{
					if( logger.isInfoEnabled()) logger.info("########## multi rows ##########");

					for (int j = 0 ; j < list.size() ; j++)
					{
						if( logger.isInfoEnabled()) logger.info("########## inner for + " + (j+1) + " ##########");

						Map map = (Map) list.get(j);
                        
						rsMap = new HashMap<String, Object>();
						rsMap.put("hostNm", 	 hostName);
						rsMap.put("taskCode",    (String)map.get("taskCode"));
						rsMap.put("luGroup", 	  (String)map.get("luGroup"));
						rsMap.put("luGroupState",(String)map.get("luGroupState"));
						rsMap.put("numLu", 	  (String)map.get("numLu"));
						rsMap.put("backupLu", 	(String)map.get("backupLu"));
						rsMap.put("upLu", 	    (String)map.get("upLu"));
						rsMap.put("usefulLu", 	(String)map.get("usefulLu"));
						rsMap.put("resLu", 	  (String)map.get("resLu"));
						rsMap.put("sendLu", 	  (String)map.get("sendLu"));
						rsMap.put("wcaSession",(String)map.get("wcaSession"));
						rsMap.put("sendCnt", 	(String)map.get("sendCnt"));
						rsMap.put("resCnt", 	  (String)map.get("resCnt"));
						rsMap.put("timeOut", 	(String)map.get("timeOut"));
						rsMap.put("sendFailCnt", (String)map.get("sendFailCnt"));
						rsMap.put("resFailCnt", 	(String)map.get("resFailCnt"));
						rsMap.put("queueWaitCnt", 	(String)map.get("queueWaitCnt"));
						rsMap.put("queueWaitMaxCnt", 	(String)map.get("queueWaitMaxCnt"));
				
						resultList.add(rsMap);
					}	
				}
			}


			if( logger.isInfoEnabled()) logger.info("########## write service ##########");
		}
		catch (Exception e)
		{
			throw e;
		}
		
		Map resultMap = new HashMap();
		resultMap.put("rows"   , resultList);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}	
	
	/**
	 * <pre>
	 * 1. 기능 : 서버 초기화, 재시작, 종료를 처리한다.
	 * 2. 처리 개요 :
	 *     -
	 * 3. 주의사항 :
	 * </pre>
	 *
	 * @author : vs.net
	 * @version : $Revision: 1.17.4.4 $
	 * @since : rts 1.0
	 * @param request
	 * @param response
	 * @param hostInfomation
	 * @throws ServletException
	 * @throws IOException
	 */
	@RequestMapping(value= "/onl/adapter/sna/snaProcessStatusMan.json", params = "cmd=LIST_STAT_CHANGE")
	public ModelAndView changeStatusNonAgent(HttpServletRequest request, HttpServletResponse response,@RequestParam HashMap<String,Object> paramMap) {
		EAIServer eaiServer = eaiServerService
				.findFirstByHostname((String) paramMap.get("hostName"))
				.orElseThrow(() -> new EMSRuntimeException("HOST를 조회 할 수 없습니다."));
		
		String msg = "";
		String type = paramMap.get("snaStatusCmd").toString();
		
		if ("INIT".equals(type))
		{
			paramMap.put("snaStatusCmd",CMD_INIT);
		}
		else if (type.startsWith("BACKUP_"))
		{
			paramMap.put("snaStatusCmd" ,("BACKUP_START".equals(type) ? CMD_START : CMD_STOP));
		}


		String result = "";
		//Sna Lu 건수 초기화
		String cmd = (String) paramMap.get("snaStatusCmd")+(String) eaiServer.getEaisevrip();
		
		logger.info("cmd :"+cmd);
		List list = null;
		
		if ("INIT".equals(cmd))
		{
			list = service.executeInit(cmd);
		}
		else
		{
			list = service.executeBackupLu(cmd);
		}
	
		if(list != null && list.size() > 0){
			for (int i = 0 ; i < list.size() ; i++)
			{
				Map map = (Map) list.get(i);
		
				result += (String)map.get("msg") + "\n";
			}
		}
	
		msg  = result;
		
		Map resultMap = new HashMap();
		resultMap.put("result"   ,msg);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/adapter/sna/snaProcessStatusMan.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;
    }	
	
}
