package utis.wall.service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.collections.map.CaseInsensitiveMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import utis.wall.common.util.CommonUtil;
import utis.wall.common.util.SEEDUtil;
import utis.wall.common.util.SHA256Util;
import utis.wall.dao.MainDao;

/**
 * @Class Name : MainController.java
 * @Description : 메인 Controller
 * @Modification Information
 * 
 *               수정일 수정자 수정내용 ------------- --------- ------------------------------- 2015. 9. 9.
 *               YJLEE 최초생성
 * 
 * @author YJLEE
 * @since 2015. 9. 9.
 * @version 1.0
 * @see
 */
@Service("MainService")
public class MainService {

	@Resource(name = "MainDao")
	private MainDao dao;

	/** 로그 객체 */
	private Log log = LogFactory.getLog(getClass());
	
	//final String key = "상황판";
	//final int[] seedKey = SEEDUtil.getSeedRoundKey("1234567890123456");
	
	@Value(value="#{globals['global.authKey']}")
	private String authKey;

	/**
	 * footer 돌발전면통제조회
	 * 
	 * @param req
	 * @return
	 */
	public Map<String, Object> getFooter(HttpServletRequest req) throws Exception {
		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_INCIDENT_CENTER");

			List<LinkedHashMap<String, Object>> list = dao.selectLinkedHashMap(paramMap);

			resultMap.put("list", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 도시 SELECTBOX조회
	 * 
	 * @param req
	 * @return
	 */
	public Map<String, Object> getSelectCity(HttpServletRequest req) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {

			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_WALL_LIST_CITY");
			List<CaseInsensitiveMap> list = dao.selectList(paramMap);

			resultMap.put("list", list);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * ROAD SELECTBOX조회
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getSelectRoad(HttpServletRequest req) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {

			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_WALL_LIST_ROAD");
			List<CaseInsensitiveMap> list = dao.selectList(paramMap);

			resultMap.put("list", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}


	/**
	 * 시내도로 CCTV 조회
	 * 
	 * @param req
	 * @return
	 */
	public Map<String, Object> getCCTV(HttpServletRequest req) throws Exception {

		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "getCCTV");

			List<LinkedHashMap<String, Object>> list = dao.selectLinkedHashMap(paramMap);
			resultMap.put("cctvList", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 돌발정보 조회
	 * 
	 * @param req
	 * @return
	 */
	public Map<String, Object> getIMS(HttpServletRequest req) throws Exception {

		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_TB_IMS_DATA");

			List<LinkedHashMap<String, Object>> list = dao.selectLinkedHashMap(paramMap);

			resultMap.put("imsList", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 고속도로/국도 CCTV조회
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getCctvRoad(HttpServletRequest req) throws Exception {

		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_CCTV");

			List<LinkedHashMap<String, Object>> list = dao.selectLinkedHashMap(paramMap);

			resultMap.put("cctvRoadList", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * getObeId 조회
	 * 
	 * @param req
	 * @return
	 */
	public Map<String, Object> getObeId(HttpServletRequest req) throws Exception {

		Map<String, Object> resultMap = new HashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_OBEXY");

			List<CaseInsensitiveMap> list = dao.selectList(paramMap);
			resultMap.put("resultList", list);

		} catch (Exception e) {

			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 고속도로/국도 CCTV(도로공사 교통센터) 조회
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getCctvRoadE05(HttpServletRequest req) throws Exception {

		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_CCTV_E05");

			List<LinkedHashMap<String, Object>> list = dao.selectLinkedHashMap(paramMap);

			resultMap.put("cctvRoadList", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * 맥어드레이스 인증 확인
	 * 
	 * @param req
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> getMacAddressAuth(HttpServletRequest req) throws Exception {

		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			String macArrS = (String) CommonUtil.getValue(paramMap, "macArr");
			if (macArrS != null) {
				String[] macArr = macArrS.split(",");
				paramMap.put("macArr", macArr);
			}
			paramMap.put("sqlId", "getMacAddressAuth");
			List<CaseInsensitiveMap> list = dao.selectList(paramMap);

			if (list.size() > 0) {
				req.getSession().setAttribute("macauth", "");
			}

			resultMap.put("count", list.size());

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	public Map<String, Object> getSignalInfo(HttpServletRequest req) throws Exception {


		LinkedHashMap<String, Object> resultMap = new LinkedHashMap<String, Object>();

		try {
			// 파라미터값 셋팅
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);

			paramMap.put("sqlId", "SELECT_SIGNAL_INFO");

			List<LinkedHashMap<String, Object>> list = dao.selectLinkedHashMap(paramMap);

			resultMap.put("list", list);

		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	public Map<String, Object> getSigInfoPhaseDetail(HttpServletRequest req) throws Exception {
		LinkedHashMap resultMap = new LinkedHashMap();

		try {
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);
			paramMap.put("sqlId", "getSigInfoPhaseDetail");
			List<LinkedHashMap<String, Object>> list = this.dao.selectLinkedHashMap(paramMap);
			resultMap.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	public Map<String, Object> getWeatherInfo(HttpServletRequest req) {
		LinkedHashMap resultMap = new LinkedHashMap();

		try {
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);
			int level = Integer.parseInt(paramMap.get("LEVEL").toString());
			if (level < 6) {
				paramMap.put("sqlId", "getWeatherInfo");
			} else if (level > 5 && level < 9) {
				paramMap.put("sqlId", "getWeatherGuInfo");
			} else {
				paramMap.put("sqlId", "getWeatherSiInfo");
			}

			List<LinkedHashMap<String, Object>> list = this.dao.selectLinkedHashMap(paramMap);
			resultMap.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	public Map<String, Object> getSpaceWeatherInfo(HttpServletRequest req) {
		LinkedHashMap resultMap = new LinkedHashMap();

		try {
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);
			int level = Integer.parseInt(paramMap.get("LEVEL").toString());
			paramMap.put("sqlId", "getSpaceWeatherInfo");
			if (level < 6) {
				paramMap.put("DONG", req.getParameter("HDONG_CODE"));
				paramMap.put("DONG_CODE", "AND B.HDONG_CODE = " + req.getParameter("HDONG_CODE"));
			} else if (level > 5 && level < 9) {
				paramMap.put("DONG", req.getParameter("HDONG_CODE").substring(0, 5));
				paramMap.put("DONG_CODE", "AND SUBSTR(B.HDONG_CODE,0,5) = "
						+ req.getParameter("HDONG_CODE").substring(0, 5));
			} else {
				paramMap.put("DONG", req.getParameter("HDONG_CODE").substring(0, 2));
				paramMap.put("DONG_CODE", "AND SUBSTR(B.HDONG_CODE,0,2) = "
						+ req.getParameter("HDONG_CODE").substring(0, 2));
			}

			List<LinkedHashMap<String, Object>> list = this.dao.selectLinkedHashMap(paramMap);
			resultMap.put("list", list);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultMap;
	}

	/**
	 * @Method getConnectionAuth
	 * @Date 2022. 11. 10.
	 * @Writer sjjung
	 * @EditHistory
	 * 
	 * @Description
	 * 
	 * @param
	 * @return Object
	 */
	public boolean getConnectionAuth(HttpServletRequest req) {
		boolean authResult = false;
		List<LinkedHashMap<String, Object>> list = null;
		ObjectMapper mapper = new ObjectMapper();
		String deviceType = CommonUtil.getDeviceType(req);
		
		try {
			Map<String, Object> paramMap = CommonUtil.getParameterMap(req);
			String requestKey = String.valueOf(paramMap.get("key"));
			String clientIP = String.valueOf(paramMap.get("ip"));

			// local test시 IPv6
			if ("0:0:0:0:0:0:0:1".equals(clientIP)) {
				clientIP = "127.0.0.1";
			}

			String[] split = clientIP.split("\\.");
			String c_class = split[0] + "." + split[1] + "." + split[2];

			if (authKey.equals(requestKey)) {
				if(!"normal".equals(deviceType)) {
					authResult = true;
				} else {
					paramMap.put("clientIp", c_class);
					paramMap.put("sqlId", "getConnectionAuth");
					list = (List<LinkedHashMap<String, Object>>) mapper
							.convertValue(dao.selectLinkedHashMap(paramMap), List.class);

					if (list.size() > 0) {
						authResult = true;
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			log.error("[ERROR getConnectionAuth: UnsupportedEncodingException]");
		} catch (Exception e) {
			log.error("[ERROR getConnectionAuth: dao result Exception]");
		}

		return authResult;
	}

	/**
	* @Method
	* getTrafficUpdateTime
	* @Date
	* 2022. 11. 29.
	* @Writer
	* sjjung
	* @EditHistory
	* 
	* @Description
	* 소통정보 범례 기준일자 표출시간 가져오기
	* @param 
	* @return Object
	*/
	public String getTrafficUpdateTime(HttpServletRequest req) {
		String time = "";
		
		try {
			time = this.dao.queryForStr("getTrafficUpdateTime");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return time;
	}
}
