package com.its.wthr.openApi.arpltnInforInqireService;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.its.wthr.openApi.arpltnInforInqireService.entity.AtmpItem;
import com.its.wthr.openApi.arpltnInforInqireService.entity.AtmpRoot;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Slf4j
@Getter
public class MsrStnAcctoRltmMesureDnsty extends ArpltnInforInqire {

    private int errorCode;
    private String errorMsg;
    private AtmpItem item = null;
//    private AtmpItem baseItem = null;

    public boolean getMsrStnAcctoRltmMesureDnsty(String apiServiceKey, String sttnName, String apiVersion) {
//        this.baseItem = new AtmpItem();
//        this.baseItem.initVal();
        this.item = null;

        //            https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty
        //            ?serviceKey=2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D
        //            &returnType=json
        //            &numOfRows=100
        //            &pageNo=1
        //            &stationName=%EB%AA%85%EB%A5%9C%EB%8F%99
        //            &dataTerm=DAILY
        //            &ver=1.3
        String apiUrl = "https://apis.data.go.kr/B552584/ArpltnInforInqireSvc/getMsrstnAcctoRltmMesureDnsty";
        String returnType = "json";

        StringBuilder urlBuilder = new StringBuilder(apiUrl);
        try {
            urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=" + apiServiceKey);
            urlBuilder.append("&" + URLEncoder.encode("returnType","UTF-8") + "=" + URLEncoder.encode(returnType, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=" + URLEncoder.encode("100", "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=" + URLEncoder.encode("1", "UTF-8"));;
            urlBuilder.append("&" + URLEncoder.encode("stationName","UTF-8") + "=" + URLEncoder.encode(sttnName, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("dataTerm","UTF-8") + "=" + URLEncoder.encode("DAILY", "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("ver","UTF-8") + "=" + URLEncoder.encode(apiVersion, "UTF-8"));
        }
        catch (UnsupportedEncodingException e) {
            this.errorCode = -99;
            this.errorMsg = "UnsupportedEncodingException.";
            log.error("MsrStnAcctoRltmMesureDnsty.getMsrStnAcctoRltmMesureDnsty: {}, UnsupportedEncodingException {}", sttnName, e.getMessage());
            return false;
        }
        log.info("{}", urlBuilder);
        String result = lookUpApi(urlBuilder);
        if (result.isEmpty()) {
            this.errorCode = -99;
            this.errorMsg = "데이터 수신 오류.";
            log.error("MsrStnAcctoRltmMesureDnsty.getMsrStnAcctoRltmMesureDnsty: Http Get Error, {}, {}", sttnName, this.errorMsg);
            return false;
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            AtmpRoot response = mapper.readValue(result, AtmpRoot.class);
            if (!"00".equals(response.getResponse().getHeader().getResultCode())) {
                this.errorCode = -99;
                this.errorMsg = getErrorMessage(response.getResponse().getHeader().getResultCode());
                log.error("MsrStnAcctoRltmMesureDnsty.getMsrStnAcctoRltmMesureDnsty: Recv Data Include ErrorCode, {}, {}, {}", sttnName, response.getResponse().getHeader().getResultCode(), this.errorMsg);
                return false;
            }
            if (response.getResponse().getBody().getItems() == null || response.getResponse().getBody().getItems().isEmpty()) {
                this.errorCode = -99;
                this.errorMsg = "Response Item Data is empty.";
                log.error("MsrStnAcctoRltmMesureDnsty.getMsrStnAcctoRltmMesureDnsty: Recv Data Item Empty, {}, {}", sttnName, this.errorMsg);
                return false;
            }
            this.errorCode = 0;
            this.errorMsg = "Success.";

            for (int ii = 0; ii < response.getResponse().getBody().getItems().size(); ii++) {
                AtmpItem obj = response.getResponse().getBody().getItems().get(ii);
                if (obj.getPm10Value24() == null) {
                    obj.setPm10Value24("");
                }
                if (obj.getPm25Value() == null) {
                    obj.setPm25Value("");
                }
                if (obj.getPm25Value24() == null) {
                    obj.setPm25Value24("");
                }
                if (obj.getPm25Grade() == null) {
                    obj.setPm25Grade("");
                }
                if (obj.getPm10Grade1h() == null) {
                    obj.setPm10Grade1h("");
                }
                if (obj.getPm25Grade1h() == null) {
                    obj.setPm25Grade1h("");
                }

                if (obj.getSo2Flag() == null) {
                    obj.setSo2Flag("");
                }
                if (obj.getCoFlag() == null) {
                    obj.setCoFlag("");
                }
                if (obj.getO3Flag() == null) {
                    obj.setO3Flag("");
                }
                if (obj.getNo2Flag() == null) {
                    obj.setNo2Flag("");
                }
                if (obj.getPm10Flag() == null) {
                    obj.setPm10Flag("");
                }
                if (obj.getPm25Flag() == null) {
                    obj.setPm25Flag("");
                }

                String msrmDt = obj.getDataTime().trim();   // YYYY-MM-DD HH:MM
                msrmDt = msrmDt.replaceAll("-", "");
                msrmDt = msrmDt.replaceAll(":", "");
                msrmDt = msrmDt.replaceAll(" ", "");
                msrmDt = msrmDt  + "00";
                obj.setDataTime(msrmDt);
                String HH = msrmDt.substring(8, 10);
                if (HH.equals("24")) {
                    // 24시인경우 날짜가 변경되지 않고 24로 넘어오기 때문에 00시로 바꿔주기위해...
                    SimpleDateFormat sdformat = new SimpleDateFormat("yyyyMMddHHmmss");
                    String sDateTime = msrmDt.substring(0,8) + "230000";
                    Date date = null;
                    try {
                        date = sdformat.parse(sDateTime);
                    } catch (ParseException e) {
                        log.error("MsrStnAcctoRltmMesureDnsty.getMsrStnAcctoRltmMesureDnsty: {}, ParseException exception.", sttnName);
                        continue;
                    }
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(date);
                    cal.add(Calendar.HOUR, 1);
                    msrmDt = new SimpleDateFormat("yyyyMMddHHmmss").format(cal.getTime());
                }
                obj.setDataTime(msrmDt);
            }

            /**
             * 가장 최근 데이터를 구한다.
             */
            int lastIdx = 0;
            this.item = response.getResponse().getBody().getItems().get(lastIdx);
            long lastDateTime = Long.parseLong(item.getDataTime());
            for (int ii = 1; ii < response.getResponse().getBody().getItems().size(); ii++) {
                AtmpItem obj = response.getResponse().getBody().getItems().get(ii);
                long currDateTime = Long.parseLong(obj.getDataTime());
                if (currDateTime > lastDateTime) {
                    lastIdx = ii;
                }
            }
            this.item = response.getResponse().getBody().getItems().get(lastIdx);
            this.item.correctValue();
        } catch (JsonProcessingException e) {
            this.errorMsg = "JsonProcessingException.";
            log.error("MsrStnAcctoRltmMesureDnsty.getMsrStnAcctoRltmMesureDnsty: {}, JsonProcessingException, {}", sttnName, e.getMessage());
            return false;
        }
        return true;
    }
}
