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

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.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.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.BizException;
import com.eactive.eai.rms.onl.common.util.DataSetUtil;
import com.eactive.eai.rms.onl.common.vo.HostInfomationForm;
import com.eactive.eai.rms.onl.manage.adapter.adapter.AdapterManService;
import com.google.gson.Gson;

import edu.emory.mathcs.backport.java.util.Collections;

/**
 * <pre>
 * 1. 기능 : Socket 상태 정보
 * 2. 처리 개요 :
 *     -
 * 3. 주의사항 :
 * </pre>
 *
 * @author : vs.net
 * @version : $Revision: 1.3 $
 * @since : rts 1.0
 */
@Controller
public class SocketProcessController extends BaseController{
	private final String AGENT_PAGE_STATUS = "adapter_socket2_agent2.jsp";

	@Autowired
    private AdapterManService adapterManService;
	
	@Autowired
	private EAIServerService eaiServerService;
	
	@RequestMapping(value= "/onl/adapter/socket/socketProcess.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/socketProcess.json",params = "cmd=LIST_INIT_COMBO")
    public ModelAndView initCombo( HttpServletRequest request,
            HttpServletResponse response) throws Exception {
    	
        List listRealTimeGroup = adapterManService.selectListRealTimeGroup();
        
		Map resultMap = new HashMap();
		resultMap.put("realTimeGroupRows"			, listRealTimeGroup);
		
		ModelAndView modelAndView = new ModelAndView("jsonView",resultMap);		
		return modelAndView;            
    }
	
	@RequestMapping(value= "/onl/adapter/socket/socketProcess.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,String searchType , String searchAdapterGroup, String searchRealTimeCd
			) throws Exception {

		List<EAIServer> serverList = eaiServerService.selectEaiServerIpList();

		if(serverList.isEmpty()) {
			throw new BizException("서버리스트가 없습니다.");
		}

		List<String> urls = new ArrayList<>();

		for (EAIServer serverMap : serverList)
		{

			String url = "http://" + serverMap.getEaisevrip() + ":"
					+ serverMap.getSevrlsnportname()
					+ HostInfomationForm.WEB_AGENT_CONTEXT_PATH
					+ AGENT_PAGE_STATUS + "?cmd=get+connection+summary"
					+ "&eaiSvrInstNm=" + serverMap.getEaisevrinstncname();
			

			logger.debug(url);
			urls.add(url);
		}

		HashMap<String,String> filter = new HashMap<>();
		if (searchAdapterGroup !=null && !"".equals(searchAdapterGroup)){
			filter.put("AdptrBzwkGroupName",searchAdapterGroup);
		}
		
		if ("ERR".equals(searchType)){
			filter.put("Status", "false");		// 어댑터 상태
			filter.put("Starting", "STOPPED");	// 기동상태
		}
		else if ("24H".equals(searchType)){
			filter.put("Param8", "1");			// 24시업무여부
		}
		else if ("24E".equals(searchType)){
			filter.put("Param8", "1");			// 24시업무여부
			filter.put("Status", "false");		// 어댑터 상태
			filter.put("Starting", "STOPPED");	// 기동상태
		}
		else if("GRP".equals(searchType))
		{
			filter.put("Param7", searchRealTimeCd);		// 24시업무명
		}
		
		
		DataSetUtil gUtil = new DataSetUtil();
		gUtil.setFilter(filter);
		List<HashMap<String, Object>> list = gUtil.flushXmlToClient(urls);
		pageVo.setTotalCount(list.size());
		
		//어댑터 업무그룹별 정렬
		String[] compareParam = {"Status","AdptrBzwkGroupName","EaiSevrInstncName"};

		MapComparator comp = new MapComparator(compareParam);
		Collections.sort(list,comp);
		
		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;
		
	}	
	@SuppressWarnings("unchecked")
	@RequestMapping(value= "/onl/adapter/socket/socketProcess.excel",params = "cmd=LIST_GRID_TO_EXCEL")
	public ModelAndView listGridToExcel(HttpServletRequest request, HttpServletResponse response, String gridData, String header, String headerTitle, String fileName, String merge) throws Exception {
		HashMap<String,Object> resultMap = new HashMap<String,Object>();

    	Gson gson = new Gson();
		HashMap<String, Object>[] list = gson.fromJson(gridData, HashMap[].class);
		
		String[] headers = gson.fromJson(header, String[].class);
		String[] headerTitles = gson.fromJson(headerTitle, String[].class);
		
		HashMap<String, Object>[] lmerge = null; 
		if (merge !=null){
			lmerge = gson.fromJson(merge, HashMap[].class);
		}
    	
    	resultMap.put("headers", headers);
    	resultMap.put("headerTitles", headerTitles);
    	resultMap.put("datas", list);
    	resultMap.put("fileName", fileName);
    	resultMap.put("merge", lmerge);
		ModelAndView modelAndView = new ModelAndView("excelView",resultMap);	
        
		return modelAndView;
    }
}

