package com.eactive.eai.rms.onl.manage.serviceinfo.eaimsg;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
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.common.util.StringUtil;
import com.eactive.eai.rms.common.context.MonitoringContext;
import com.eactive.eai.rms.common.spring.BaseController;
import com.eactive.eai.rms.common.spring.LocaleMessage;
import com.eactive.eai.rms.common.util.CamelCaseUtil;
import com.eactive.eai.rms.onl.common.exception.BizException;
import com.eactive.eai.rms.onl.manage.rule.upload.IoMapLoaderKey;

@Controller
@SuppressWarnings({"rawtypes", "unchecked"})
public class EaiMsgCmFtpErrorController extends BaseController {
	private static final Logger logger = Logger.getLogger(EaiMsgCmFtpErrorController.class);
	
	@Autowired
	@Qualifier("localeMessage")
	private LocaleMessage localeMessage;
	
	@Autowired
	@Qualifier("eaiMsgCmFtpService")
	private EaiMsgCmFtpService service;
	
	@Autowired
	@Qualifier("monitoringContext")
	private MonitoringContext monitoringContext;	
	
	@RequestMapping(value="/onl/admin/service/eaiMsgCmFtpError.view")
	public 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/service/eaiMsgCmFtpError.json", params = "cmd=LIST_FAIL")
	public ModelAndView localFailFileList(HttpServletRequest request) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Properties prop = monitoringContext.getProperties();
		String path = prop.getProperty(MonitoringContext.CM_FAIL_PATH  , "/dat/eaiData/engineData/fail/");
		List<HashMap> cmList = new ArrayList<HashMap>();
		try {
			String[] fileList = service.getLocalFileList(path);
			if (fileList != null) {
				for (String name : fileList) {
					HashMap map = new HashMap();
					String[] s = name.split("_");
					Calendar cal = Calendar.getInstance();
					cal.setTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(s[0]));
					
					map.put("FILE_NM", name);
					map.put("DATE", (cal.get(Calendar.YEAR) +"년  "
						+ String.format("%02d", cal.get(Calendar.MONTH)+1) +"월 "
						+ String.format("%02d", cal.get(Calendar.DAY_OF_MONTH)) +"일 "
						+ String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)) +"시 "
						+ String.format("%02d", cal.get(Calendar.MINUTE)) +"분 "
						+ String.format("%02d", cal.get(Calendar.SECOND)) +"초"));
					map.put("USER", s[1]);
					map.put("SYSTEM", IoMapLoaderKey.getSysCdNm(s[2]));
					cmList.add(map);
				}
				resultMap.put("cmList", cmList);
			}
		} catch (BizException be) {
			logger.error(be.getMessage(),be);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception(localeMessage.getString("errors.checklog"));
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/admin/service/eaiMsgCmFtpError.json", params = "cmd=DETAIL_JOB_FILE")
	public ModelAndView detailLocalFile(HttpServletRequest request, @RequestParam HashMap paramMap) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		Properties prop = monitoringContext.getProperties();
		String path = prop.getProperty(MonitoringContext.CM_DOWNLOAD_PATH  , "/dat/eaiData/engineData/download/");
		
		try {
			String fileName = (String)paramMap.get("fileName");
			Map detail = service.getLocalFileDetail(path, fileName);
			resultMap.put("Detail", detail);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception(localeMessage.getString("errors.checklog"));
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}

	@RequestMapping(value= "/onl/admin/service/eaiMsgCmFtpError.json", params = "cmd=DETAIL_FAIL_FILE")
	public ModelAndView detailLocalFailFile(HttpServletRequest request, @RequestParam HashMap paramMap) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();

		Properties prop = monitoringContext.getProperties();
		String path = prop.getProperty(MonitoringContext.CM_FAIL_PATH  , "/dat/eaiData/engineData/fail/");
		
		try {
			String fileName = (String)paramMap.get("fileName");
			Map detail = service.getLocalFileDetail(path,fileName);
			resultMap.put("Detail", detail);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception(localeMessage.getString("errors.checklog"));
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	@RequestMapping(value= "/onl/admin/service/eaiMsgCmFtpError.json", params = "cmd=LIST_JOB")
	public ModelAndView jobFileList(HttpServletRequest request) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		Properties prop = monitoringContext.getProperties();
		String path = prop.getProperty(MonitoringContext.CM_DOWNLOAD_PATH  , "/dat/eaiData/engineData/download/");
		List<HashMap> cmList = new ArrayList<HashMap>();
		try {
			String[] fileList = service.getLocalFileList(path);
			if(fileList != null){ //취약점소스 수정 2020.08.27
				for (String name : fileList) {
					HashMap map = new HashMap();
					String[] s = name.split("_");
					Calendar cal = Calendar.getInstance();
					cal.setTime(new SimpleDateFormat("yyyyMMddHHmmss").parse(s[0]));
					
					map.put("FILE_NM", name);
					map.put("DATE", (cal.get(Calendar.YEAR) +"년  "
						+ String.format("%02d", cal.get(Calendar.MONTH)+1) +"월 "
						+ String.format("%02d", cal.get(Calendar.DAY_OF_MONTH)) +"일 "
						+ String.format("%02d", cal.get(Calendar.HOUR_OF_DAY)) +"시 "
						+ String.format("%02d", cal.get(Calendar.MINUTE)) +"분 "
						+ String.format("%02d", cal.get(Calendar.SECOND)) +"초"));
					map.put("USER", s[1]);
					map.put("SYSTEM", IoMapLoaderKey.getSysCdNm(s[2]));
					cmList.add(map);
				}
			}
			resultMap.put("cmList", cmList);
			
		} catch (BizException be) {
			logger.error(be.getMessage(),be);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception(localeMessage.getString("errors.checklog"));
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/admin/service/eaiMsgCmFtpError.json", params = "cmd=DELETE_FILES")
	public ModelAndView deleteFiles(HttpServletRequest request, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String localFiles = StringUtil.getNullStr(paramMap.get("LocalFiles"));
		String ftpFiles = StringUtil.getNullStr(paramMap.get("FtpFiles"));
		
		try {
			boolean ret = service.deleteFiles(localFiles, ftpFiles);
			if (!ret) {
				throw new BizException("파일 삭제 중 에러가 발생하였습니다.");
			}
			resultMap.put("message", "성공적으로 삭제 되었습니다.");
		} catch (BizException be) {
			throw new Exception(be.getMessage(),be);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception(localeMessage.getString("errors.checklog"));
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	
	@RequestMapping(value= "/onl/admin/service/eaiMsgCmFtpError.json", params = "cmd=CHANGE_DIR")
	public ModelAndView ftpUpload(HttpServletRequest request, @RequestParam HashMap<String,Object> paramMap) throws Exception {
		HashMap<String, Object> resultMap = new HashMap<String, Object>();
		String localFiles = StringUtil.getNullStr(paramMap.get("LocalFiles"));
		
		try {
			service.moveForRetry(localFiles);
			resultMap.put("message", "성공적으로 업로드 되었습니다.");
		}  catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw new Exception(e.getMessage(),e);
		}
		
		ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
		return modelAndView;
	}
	

	
}
