package com.style24.core.biz.thirdparty;

import java.net.URI;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.google.gson.Gson;
import com.style24.persistence.domain.NaverLowestPrice;

import lombok.extern.slf4j.Slf4j;

/**
 * 네이버 최저가 조회 API
 * 
 * @author gagamel
 * @since 2020. 12. 3
 */
@Component
@Slf4j
public class NaverLowestPriceApi {

	// URL
	private String apiUrl = "https://openapi.naver.com/v1/search/shop.json";

	// Client ID
	private String clientId = "x5FGDO3Q9kNZVG9SnDY6";

	// Client Secret
	private String clientSecret = "tRRng56dgN";

	@Autowired
	private RestTemplate restTemplate;

	@PostConstruct
	public void init() {
		log.debug("\n\n---- NaverLowestPriceApi initialization started ----");
		log.debug("apiUrl: [{}]", apiUrl);
		log.debug("clientId: [{}]", clientId);
		log.debug("clientSecret: [{}]", clientSecret);
		log.debug("\n--- NaverLowestPriceApi initialization completed ----\n");
	}

	/**
	 * 상품의 최저가 조회
	 * @param goodsCd - 상품코드
	 * @return 상품의 최저가 정보
	 * @throws Exception
	 * @author gagamel
	 * @since 2020. 12. 3
	 */
	public NaverLowestPrice getLowestPrice(String goodsCd) throws Exception {
		// Header
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		headers.add("X-Naver-Client-Id", clientId);
		headers.add("X-Naver-Client-Secret", clientSecret);

		String requestUrl = apiUrl + "?query=" + URLEncoder.encode(goodsCd, "UTF-8") + "&display=1&sort=asc";
		log.info("requestUrl: {}", requestUrl);
		URI url = URI.create(requestUrl);

		// GET방식으로 호출
		HttpEntity<String> request = new HttpEntity<String>(headers);
		ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
		log.info("responseEntity.getStatusCode(): {} ", responseEntity.getStatusCode());

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

		if (!responseEntity.getStatusCode().equals(HttpStatus.OK)) {
			return null;
		}

		Gson gson = new Gson();
		return gson.fromJson(responseJson, NaverLowestPrice.class);
	}

	/**
	 * 상품의 최저가 조회
	 * @param goodsCdList - 상품코드 목록
	 * @return 상품의 최저가 목록
	 * @throws Exception
	 * @author gagamel
	 * @since 2020. 12. 3
	 */
	public Collection<NaverLowestPrice> getLowestPriceList(Collection<String> goodsCdList) throws Exception {
		if (goodsCdList == null || goodsCdList.isEmpty()) {
			throw new IllegalStateException("조회할 상품코드 정보가 없습니다.");
		}

		Collection<NaverLowestPrice> lpriceList = new ArrayList<>();

		for (String goodsCd : goodsCdList) {
			log.info("[getLowestPriceList] goodsCd = {}", goodsCd);
			NaverLowestPrice lprice = this.getLowestPrice(goodsCd);
			if (lprice != null) {
				lpriceList.add(lprice);
			}
		}

		return lpriceList;
	}

}
