package com.style24.core.biz.thirdparty;

import java.net.URI;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.style24.core.support.message.TscMessageByLocale;
import com.style24.persistence.domain.KakaoPay;

import lombok.extern.slf4j.Slf4j;

/**
 * 카카오페이 API
 *
 * @author card007
 * @since 2021. 03. 04
 */
@Component
@Slf4j
public class KakaoPayApi {

	@Autowired
	private Environment env;

	@Autowired
	private TscMessageByLocale message;

	@Autowired
	private RestTemplate restTemplate;

	private String adminKey;

	@PostConstruct
	public void init() {
		adminKey = env.getProperty("kakao.adminKey");

		log.info("\n\n---- KakaoPay initialization started ----");
		log.info("adminKey: [{}]", adminKey);
		log.info("\n--- KakaoPay initialization completed ----\n");
	}

	/**
	 * 카카오페이 API
	 *
	 * @param Order
	 * @return GagaMap
	 * @author card007
	 * @since 2021. 03. 03
	 */
	public KakaoPay kakaoPaymentApi(MultiValueMap<String, String> params, String apiUrl) {
		KakaoPay pay;
		try {
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
			headers.set("Authorization", "KakaoAK " + adminKey);

			HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
			URI url = URI.create(apiUrl);

			ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
			log.info("responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());

			String jsonResult = responseEntity.getBody();
			log.info("responseEntity.getBody(): {} ", jsonResult);

			Gson gson = new GsonBuilder().create();
			pay = gson.fromJson(jsonResult, KakaoPay.class);
			pay.setStatusCode(responseEntity.getStatusCode().value());

		} catch (Exception e) {
			e.printStackTrace();
			throw new IllegalStateException(message.getMessage("FAIL_0004"));
		}

		return pay;
	}
}
