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

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.data.entity.onl.server.EAIServer;
import com.eactive.eai.rms.common.combo.ComboService;
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.common.exception.BizException;
import com.eactive.eai.rms.onl.common.exception.EMSRuntimeException;
import com.eactive.eai.rms.onl.common.util.CallAgentUtil;

@Controller
public class PuInfoController extends BaseController{
	
	@Autowired
	private MonitoringContext monitoringContext;
	
    @Autowired
    private ComboService comboService; 
    
    @Autowired
    private EAIServerService eaiServerService;
    
    private final String AGENT_PAGE = "run_command.jsp";

	
	@RequestMapping(value= "/onl/admin/sna/puInfoMan.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/admin/sna/puInfoMan.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/admin/sna/puInfoMan.json", params = "cmd=LIST")
	private ModelAndView selectList(HttpServletRequest request,
			JsonPageVo pageVo ,@RequestParam HashMap<String,Object> paramMap) throws Exception {
		
		String searchHostNm = (String)paramMap.get("searchHostNm");
		EAIServer eaiServer = eaiServerService
				.findFirstByHostname(searchHostNm)
				.orElseThrow(() -> new EMSRuntimeException("호스트를 조회 할 수 없습니다."));
		

		//sh 프라퍼티로 
        String command =  monitoringContext.getStringProperty(MonitoringContext.SNA_PU_INFO_CMD, 
        		"/fshome/greai/eaiadm/script/sna/sna_pu_status.sh");
        
        logger.info("command : "+command);
        
		String url = "http://" + eaiServer.getEaisevrip() + ":"
					+ eaiServer.getSevrlsnportname()
					+ "/agent/"
					+ AGENT_PAGE
					+ "?command=" + command
					;
		
		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;
		
	}
}
