package com.style24.front.biz.thirdparty;

import com.gagaframework.web.parameter.GagaMap;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
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.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.net.URI;

@Component
@Slf4j
public class GoogleReCaptcha {
	@Autowired
	private Environment env;

	@Autowired
	private RestTemplate restTemplate;

	private String siteKey;
	private String secretKey;
	private String verifyUrl;

	@PostConstruct
	public void init() {
		siteKey = env.getProperty("google.siteKey");
		secretKey = env.getProperty("google.secretKey");
		verifyUrl = env.getProperty("google.recaptchaVerifyUrl");

		log.info("\n\n---- Google initialization started ----");
		log.info("siteKey: [{}]", siteKey);
		log.info("secretKey: [{}]", secretKey);
		log.info("verifyUrl: [{}]", verifyUrl);
		log.info("\n--- Google initialization completed ----\n");
	}

	public GagaMap getVerify(String token) {
		GagaMap resultMap = new GagaMap();
		try {
			MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
			params.add("secret", secretKey);
			params.add("response", token);

			// Header
			HttpHeaders headers = new HttpHeaders();
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

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

			// POST방식으로 호출
			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();
			resultMap = gson.fromJson(jsonResult, GagaMap.class);
		} catch (Exception e) {
			log.error(e.getMessage());
		}
		return  resultMap;
	}



}
