package com.eactive.eai.rms.bat.manage.rule.schedule;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.eactive.eai.rms.bat.manage.comm.server.BatServerService;
import com.eactive.eai.rms.bat.manage.rule.inter.BatInterfaceDao;
import com.eactive.eai.rms.bat.manage.rule.schedule.vo.SchedulerMonitorVO;
import com.eactive.eai.rms.bat.manage.rule.schedule.vo.SchedulerReport;
import com.eactive.eai.rms.bat.manage.rule.schedule.vo.SchedulerReportJobDetail;
import com.eactive.eai.rms.common.base.BaseService;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class BatSchedulerMonitorService extends BaseService {
	
	@Autowired
	private BatInterfaceDao interfaceDao;
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Autowired @Qualifier("batServerService")
    private BatServerService batServerService;
	
	public List<SchedulerMonitorVO> selectList(Map<String, Object> paramMap) throws Exception {

		List<SchedulerMonitorVO> selectList = interfaceDao.selectSchedulerMonitorVOList(paramMap);
		
		Map<String, String> hostName_requestUrl_map = getRequestUrlMap("schedulerReport.jsp?reportType=summary");
		
		String response = httpCallAndGetResponse(hostName_requestUrl_map);
		
		SchedulerReport report = 
				new ObjectMapper()
				.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
				.readValue(response, SchedulerReport.class);
		
		setMemoryValuesToRow(selectList, report);
		
		return selectList;
	}
	
	public Integer selectCount(Map<String, Object> paramMap) throws Exception {
		return interfaceDao.selectSchedulerMonitorVOListCount(paramMap);
	}
	
		private Map<String, String> getRequestUrlMap(String jspName) throws Exception {
			
			DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceType(DataSourceTypeManager.BAT));
			
			List<HashMap<String, Object>> eaiServerIpPort = batServerService.getEaiServerIpPort();
			
			Map<String, String> resultMap = new HashMap<>();
			
			for(HashMap<String, Object> row : eaiServerIpPort) {
				String hostName = String.valueOf(row.get("HOSTNAME"));
//				String requestUrl = "";
//				if(ContainerUtil.get() == ContainerUtil.TOMCAT) {
//					requestUrl = "http://" + hostName + ":" + String.valueOf(row.get("EAISVRLSNPORT")) + "/BATWeb/" + jspName;
//				} else {
//					requestUrl = "http://" + hostName + ".pobis.kr:" + String.valueOf(row.get("EAISVRLSNPORT")) + "/BATWeb/" + jspName;
//				}
				String hostIp = String.valueOf(row.get("EAISVRIP"));
				String requestUrl = "http://" + hostIp + ":" + String.valueOf(row.get("EAISVRLSNPORT")) + "/BATWeb/" + jspName;
				resultMap.put(hostName, requestUrl);
				
			}
			
			return resultMap;
		}
		
		private String httpCallAndGetResponse(Map<String, String> hostName_requestUrl_map) throws Exception {
			StringBuilder errorBuilder = new StringBuilder();
			for(Entry<String, String> entry : hostName_requestUrl_map.entrySet()) {
				String requestUrl = entry.getValue();
				HttpHeaders headers = new HttpHeaders();
				HttpEntity<String> entity = new HttpEntity<>(headers);
				ResponseEntity<String> response = restTemplate.exchange(requestUrl, HttpMethod.GET, entity, String.class);
				if(200 <= response.getStatusCodeValue() || response.getStatusCodeValue() < 300) {
					return response.getBody();
				} else {
					errorBuilder.append(response.getBody());
					errorBuilder.append(" ");
					errorBuilder.append(System.lineSeparator());
				}
			}
			throw new Exception(errorBuilder.toString());
		}
		
		private void setMemoryValuesToRow(List<SchedulerMonitorVO> selectList, SchedulerReport report) {
			
			List<SchedulerReportJobDetail> jobDetails = report.getJobDetails();
			
			for (SchedulerMonitorVO row : selectList) {
				
				SchedulerReportJobDetail memory = jobDetails.stream().filter(item -> row.getInterfaceId().equals(item.getKeyName())).findAny().orElse(null);
				
				if(memory == null) {
					row.setOnMemory(false);
					continue;
				} else {
					row.setOnMemory(true);
					
					if (memory.getTriggers().size() > 0)
					{
						row.setTriggerPreviousFireTime(memory.getTriggers().get(0).getPreviousFireTime());
						row.setTriggerNextFireTime(memory.getTriggers().get(0).getNextFireTime());
						row.setTriggerState(memory.getTriggers().get(0).getTriggerState());
					}
					
					row.setConcurrentExectionDisallowed(memory.isConcurrentExectionDisallowed());
					row.setPersistJobDataAfterExecution(memory.isPersistJobDataAfterExecution());
					row.setDurable(memory.isDurable());
				}
				
			}
		
		}
	
}
