package cokr.xit.ens.modules.ktsigntalk.direct.service.support;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * <ul>
 * <li>업무 그룹명: KT 인증톡 서비스</li>
 * <li>설 명: </li>
 * <li>작성일: 2021. 11. 18. 오후 5:01:36
 * </ul>
 *
 * @author 박민규
 */
@Slf4j
@Component
public class KtSigntalkApi {

    @Value("${contract.kt.signtalk.direct.host}")
    private String HOST;
    @Value("${contract.kt.signtalk.direct.api.ping}")
    private String API_PING;
    @Value("${contract.kt.signtalk.direct.api.token}")
    private String API_TOKEN;
    @Value("${contract.kt.signtalk.direct.api.bulksend}")
    private String API_BULKSEND;
    @Value("${contract.kt.signtalk.direct.api.bulkstatus}")
    private String API_BULKSTATUS;
    @Value("${contract.kt.signtalk.direct.api.agrees}")
    private String API_AGREES;


    /**
     * Ping Test Url
     */
//	설명: 고지서 서버 ping check url
//	호출경로: GET /api/mns/status
//	반환값:
//      1. OpenApi 서비스 정상 : {“code”:”0000”,”message”:”OK”}
//      2. OpenApi 서비스 중지 : {“code”:”6001”,”message”:"openapi 서비스 중지"}
    public ResponseEntity<String> ping(String accessToken) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));
        headers.set("Authorization", String.format("Bearer %s", accessToken));

       
        StringBuilder url = new StringBuilder();
        url.append(this.HOST)
                .append(API_PING);

       
        ResponseEntity<String> resp = this.callApi(HttpMethod.GET, url.toString(), null, headers);
        return resp;
    }

    /**
     * 수신동의거부 조회
     */
//	설명: 수신동의거부 조회
//	호출경로: GET /api/mns/agrees
    public ResponseEntity<String> agrees(String accessToken, String serviceCd, String serviceKey) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));
        headers.set("Authorization", String.format("Bearer %s", accessToken));

       
        StringBuilder url = new StringBuilder();
        url.append(this.HOST)
                .append(API_AGREES);

       
        String querystring = String.format("service_cd=%s&service_key=%s", serviceCd, serviceKey);


       
        ResponseEntity<String> resp = this.callApi(HttpMethod.GET, url.toString(), querystring, headers);
        return resp;
    }


    /**
     * 토큰 유효성 검증(Redirect URL  접속 허용/불허)
     */
//	설명: RedirectUrl로 전달된 nonce 값의 검증을 요청
//	호출경로: POST /api/mns/token/status
//  Content-Type: application/json
    public ResponseEntity<String> token(String accessToken, String serviceCd, String serviceKey, String srcKey, String token) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));
        headers.set("Authorization", String.format("Bearer %s", accessToken));

       
        StringBuilder url = new StringBuilder();
        url.append(this.HOST)
                .append(API_TOKEN);

        String jsonStr = "{" +
                "    \"service_cd\": \"" + serviceCd + "\"" +
                "    \"service_key\": \"" + serviceKey + "\"" +
                "    \"src_key\": \"" + srcKey + "\"" +
                "    ,\"token\": \"" + token + "\"" +
                "}";

       
        ResponseEntity<String> resp = this.callApi(HttpMethod.POST, url.toString(), jsonStr, headers);
        return resp;
    }


    /**
     * 대량(bulk) 문서발송 요청
     * -.이용기관 서버에서 API 서버로 대량(bulk) 문서발송 처리를 요청합니다.
     */
//	설명: 네이버 고지서 서버에 1건 이상의 고지서 발송 요청
//	호출경로: POST /api/mns/req
//  Content-Type: application/json
    public ResponseEntity<String> bulkSend(String accessToken, String jsonStr) {
       
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));
        headers.set("Authorization", String.format("Bearer %s", accessToken));

       
        StringBuilder url = new StringBuilder();
        url.append(this.HOST)
                .append(API_BULKSEND);

       
        ResponseEntity<String> resp = this.callApi(HttpMethod.POST, url.toString(), jsonStr, headers);
        return resp;

    }


    /**
     * 대량(bulk) 문서 상태 조회 API
     */
//	설명: API 서버에 고지서 상태 조회 요청
//	호출경로: POST /api/mns/rsp
    public ResponseEntity<String> bulkStatus(String accessToken, String jsonStr) {
       
        HttpHeaders headers = new HttpHeaders();
//		headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setContentType(new MediaType(MediaType.APPLICATION_JSON, Charset.forName("utf-8")));
        headers.set("Authorization", String.format("Bearer %s", accessToken));

       
        StringBuilder url = new StringBuilder();
        url.append(this.HOST)
                .append(API_BULKSTATUS);

       
        ResponseEntity<String> resp = this.callApi(HttpMethod.POST, url.toString(), jsonStr, headers);
        return resp;
    }


    /**
     * <pre>메소드 설명: API 호출
     * </pre>
     *
     * @param method
     * @param url
     * @param body
     * @param headers
     * @return ResponseEntity 요청처리 후 응답객체
     * @author: 박민규
     * @date: 2021. 8. 4.
     * @apiNote: 사이트 참조 https://e2e2e2.tistory.com/15
     */
    private ResponseEntity<String> callApi(HttpMethod method, String url, String body, HttpHeaders headers) {

        StringBuffer sb = new StringBuffer();
        ResponseEntity<String> responseEntity = null;
        try {
           
            HttpEntity<?> entity = null;
            UriComponents uri = null;
            switch (method) {
                case GET:
                    entity = new HttpEntity<>(headers);
                    uri = UriComponentsBuilder
                            .fromHttpUrl(String.format("%s?%s", url, body == null ? "" : body))
//							.encode(StandardCharsets.UTF_8)	//"%"기호가 "%25"로 인코딩 발생하여 주석처리 함.
                            .build(false);
                    break;
                case POST:
                    entity = new HttpEntity<>(body, headers);
                    uri = UriComponentsBuilder
                            .fromHttpUrl(url)
                            .encode(StandardCharsets.UTF_8)
                            .build();
                    break;

                default:
                    break;
            }


           
            HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
            factory.setConnectTimeout(3000);
//			factory.setReadTimeout(3000);
            factory.setReadTimeout(10000);
            RestTemplate restTemplate = new RestTemplate(factory);
            sb.append("\n  url => " + uri.toString())
                    .append("\n  method => " + method)
                    .append("\n  headers => " + entity.getHeaders().toString())
                    .append("\n  body => " + entity.getBody());
            responseEntity = restTemplate.exchange(URI.create(uri.toString()), method, entity, String.class); 

            /*
             * HttpStatus 정보 확인 방법
             * 	-.코드: responseEntity.getStatusCodeValue()
             * 	-.메시지: responseEntity.getStatusCode()
             */

        } catch (HttpServerErrorException e) {
            responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
            log.error("call API 서버오류[url => {} param => {} error => {}]", url, body, e.getMessage());
        } catch (HttpClientErrorException e) {
            responseEntity = new ResponseEntity<String>(e.getResponseBodyAsString(), e.getStatusCode());
            log.error("call API 클라이언트오류[url => {} param => {} error => {}]", url, body, e.getMessage());
        } catch (RestClientException e) {   
            responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.REQUEST_TIMEOUT);
            log.error("RestAPI 호출 오류[url => {} param => {} error => {}]", url, body, e.getMessage());
        } catch (Exception e) {
            responseEntity = new ResponseEntity<String>(e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
            log.error("call API 기타오류[url => {} param => {} error => {}]", url, body, e.getMessage());
        } finally {
            log.info("KT 인증톡 API\n[ REQUEST ]-----------------------------------------------------------------------\n{}\n[ RESPONSE ]-----------------------------------------------------------------------\n{}", sb.toString(), responseEntity.getBody());
        }

       
        return responseEntity;
    }

}

