package com.its.wthr;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.its.wthr.openApi.arpltnInforInqireService.MsrStnAcctoRltmMesureDnsty;
import com.its.wthr.openApi.vilageFcstInfoService.UltraSrtNcstData;
import com.its.wthr.openApi.vilageFcstInfoService.entity.VilageItems;
import com.its.wthr.openApi.vilageFcstInfoService.entity.VilageRoot;
import lombok.extern.slf4j.Slf4j;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.jasypt.salt.StringFixedSaltGenerator;
import org.junit.jupiter.api.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@Slf4j
//@SpringBootTest(classes = WthrCommServerApplication.class)
//@AutoConfigureMockMvc
//@SpringBootTest(
//        webEnvironment = SpringBootTest.WebEnvironment.MOCK,
//        properties = "spring.config.location ="+
//                "classpath:/application.yml"+
//                ",classpath:/database.yaml"
//)
public class WthrCommServerApplicationTests {

    @Test
    void jasypt() {
        String encKey = "asdkjfaslkjflkajslfjkajlkf";
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();

        // ==> SimpleStringPBEConfig 사용시 아래 3개 반드시 설정해야함
        config.setPassword(encKey);                                         // 암호화에 사용할 키
        config.setPoolSize(1);                                              // Pool Size
        config.setSaltGenerator(new StringFixedSaltGenerator("fixedSalt")); // 고정으로 암호화(Default: Random)
        //config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        //config.setAlgorithm("PBEWithMD5AndTripleDES");
        config.setAlgorithm("PBEWithMD5AndDES"); // Jasypt 를 이용한 암호화 알고리즘
        config.setProviderName("SunJCE");
        config.setKeyObtentionIterations("10000");
        config.setStringOutputType("base64");
        /*private Boolean proxyPropertySources = false;
        private String bean = "jasyptStringEncryptor";
        private String password;
        private String algorithm = "PBEWithMD5AndDES";
        private String keyObtentionIterations = "1000";
        private String poolSize = "1";
        private String providerName = null;
        //config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        private String saltGeneratorClassname = "org.jasypt.salt.RandomSaltGenerator";
        private String stringOutputType = "base64";*/
        encryptor.setConfig(config);

        String yiits = encryptor.encrypt("adits");
        String rutis = encryptor.encrypt("adits");
        log.info("{}", yiits);
        log.info("{}", rutis);
    }

    @Test
    void testGetUltraSrtNcst() {
        // 초단기실황조회, https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst?serviceKey=2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D&pageNo=1&numOfRows=1000&dataType=json&base_date=20210628&base_time=0600&nx=55&ny=127
        UltraSrtNcstData info = new UltraSrtNcstData();
        String apiUrl = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtNcst";
        String serviceKey = "2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D";
        String nx = "91";
        String ny = "106";
        String baseDate = info.getBaseDate();
        String baseTime = info.getBaseTime();
        String dataType = "json";

        StringBuilder urlBuilder = new StringBuilder(apiUrl);
        try {
            urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=" + serviceKey);
            urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=1");
            urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=1000");
            urlBuilder.append("&" + URLEncoder.encode("dataType","UTF-8") + "=" + URLEncoder.encode(dataType, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("base_date","UTF-8") + "=" + URLEncoder.encode(baseDate, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("base_time","UTF-8") + "=" + URLEncoder.encode(baseTime, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("nx","UTF-8") + "=" + URLEncoder.encode(nx, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("ny","UTF-8") + "=" + URLEncoder.encode(ny, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        log.info("{}", urlBuilder);
        String result = info.lookUpApi(urlBuilder);
        log.info("{}", result);

        ObjectMapper mapper = new ObjectMapper();
        try {
            VilageRoot response = mapper.readValue(result, VilageRoot.class);
            log.info("{}", response);

            if (response != null && response.getResponse() != null && response.getResponse().getBody() != null) {
                VilageItems items = response.getResponse().getBody().getItems();
                if (items.getItem() != null) {
                    items.getItem().forEach(obj -> {
                        log.info("{}", obj);
                    });
                }
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }


    @Test
    void testGetUltraSrtFcst() {
        // 초단기예보조회, https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst?serviceKey=2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D&pageNo=1&numOfRows=1000&dataType=json&base_date=20230913&base_time=1130&nx=55&ny=127
        UltraSrtNcstData info = new UltraSrtNcstData();
        String apiUrl = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getUltraSrtFcst";
        String serviceKey = "2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D";
        String nx = "91";
        String ny = "106";
        String baseDate = info.getBaseDate();
        String baseTime = info.getBaseTime();
        String dataType = "json";

        StringBuilder urlBuilder = new StringBuilder(apiUrl);
        try {
            urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=" + serviceKey);
            urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=1");
            urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=1000");
            urlBuilder.append("&" + URLEncoder.encode("dataType","UTF-8") + "=" + URLEncoder.encode(dataType, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("base_date","UTF-8") + "=" + URLEncoder.encode(baseDate, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("base_time","UTF-8") + "=" + URLEncoder.encode(baseTime, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("nx","UTF-8") + "=" + URLEncoder.encode(nx, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("ny","UTF-8") + "=" + URLEncoder.encode(ny, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        log.info("{}", urlBuilder);
        String result = info.lookUpApi(urlBuilder);
        log.info("{}", result);

        ObjectMapper mapper = new ObjectMapper();
        try {
            VilageRoot response = mapper.readValue(result, VilageRoot.class);
            log.info("{}", response);

            if (response != null && response.getResponse() != null && response.getResponse().getBody() != null) {
                VilageItems items = response.getResponse().getBody().getItems();
                if (items.getItem() != null) {
                    items.getItem().forEach(obj -> {
                        log.info("{}", obj);
                    });
                }
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    void testGetVilageFcst() {
        // 단기예보조회,   https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst?serviceKey=2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D&pageNo=1&numOfRows=1000&dataType=json&base_date=20230913&base_time=1100&nx=88&ny=106
        UltraSrtNcstData info = new UltraSrtNcstData();
        String apiUrl = "https://apis.data.go.kr/1360000/VilageFcstInfoService_2.0/getVilageFcst";
        String serviceKey = "2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D";
        String nx = "91";
        String ny = "106";
        String baseDate = info.getBaseDate();
        String baseTime = info.getBaseTime();
        String dataType = "json";

        StringBuilder urlBuilder = new StringBuilder(apiUrl);
        try {
            urlBuilder.append("?" + URLEncoder.encode("serviceKey","UTF-8") + "=" + serviceKey);
            urlBuilder.append("&" + URLEncoder.encode("pageNo","UTF-8") + "=1");
            urlBuilder.append("&" + URLEncoder.encode("numOfRows","UTF-8") + "=1000");
            urlBuilder.append("&" + URLEncoder.encode("dataType","UTF-8") + "=" + URLEncoder.encode(dataType, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("base_date","UTF-8") + "=" + URLEncoder.encode(baseDate, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("base_time","UTF-8") + "=" + URLEncoder.encode(baseTime, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("nx","UTF-8") + "=" + URLEncoder.encode(nx, "UTF-8"));
            urlBuilder.append("&" + URLEncoder.encode("ny","UTF-8") + "=" + URLEncoder.encode(ny, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }

        log.info("{}", urlBuilder);
        String result = info.lookUpApi(urlBuilder);
        log.info("{}", result);

        ObjectMapper mapper = new ObjectMapper();
        try {
            VilageRoot response = mapper.readValue(result, VilageRoot.class);
            log.info("{}", response);

            if (response != null && response.getResponse() != null && response.getResponse().getBody() != null) {
                VilageItems items = response.getResponse().getBody().getItems();
                if (items.getItem() != null) {
                    items.getItem().forEach(obj -> {
                        log.info("{}", obj);
                    });
                }
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Test
    void testGetAtmp() {
        MsrStnAcctoRltmMesureDnsty request = new MsrStnAcctoRltmMesureDnsty();
        boolean result = request.getMsrStnAcctoRltmMesureDnsty("2y3qwo%2BwhlG6E%2BZfcyDKLMCr5Lp4gy%2BNgGuvWmgAdq7O%2Bf%2Fs4DPQz2ZD1rzDLowBq%2F6pfSi5F6UWlyM5meRiaw%3D%3D", "명륜동", "1.3");
        if (result) {
            log.info("{}", request.getItem());
            log.info("{}", request.getErrorMsg());
        }
        else {
            log.info("{}", request.getErrorMsg());
        }
    }

}
