package cokr.xit.ens.core.monitor.slack.support;

import cokr.xit.ens.core.exception.EnsException;
import cokr.xit.ens.core.exception.code.EnsErrCd;
import cokr.xit.ens.core.utils.CmmnUtil;
import cokr.xit.ens.core.utils.MapDeserailizer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Slf4j
@Builder
public class ChannelGetter {

    private String TOKEN;
    private String API_URL;
    private String email;


    public String execute() {

        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<String> requestEntity = new HttpEntity<>(this.createHeaders(ContentType.APPLICATION_FORM_URLENCODED));
        ResponseEntity<String> responseEntity = restTemplate.exchange(String.format("%s?email=%s", API_URL, email), HttpMethod.GET, requestEntity, String.class);
        log.info("====================================================================");
        log.info("==== Slack getSlackId Response... ====");
        log.info(String.format("[ HttpStatusCode %d ]", responseEntity.getStatusCode().value()));
        log.info(responseEntity.getBody());
        log.info("====================================================================");

        Map<String, Object> result = gson.fromJson(responseEntity.getBody(), Map.class);
        if(!CmmnUtil.isEmpty(result.get("error")))
            throw new EnsException(EnsErrCd.ERR620, String.format("Slack ID 조회 실패. %s [ email %s API_URL %s TOKEN %s ]", (String) result.get("error"), email, API_URL, TOKEN) );

        Map<String, String> profile = (Map<String, String>) result.get("user");
        String id = profile.get("id");
        return id;

    }

    protected final Gson gson = new GsonBuilder().registerTypeAdapter(Map.class, new MapDeserailizer()).disableHtmlEscaping().create();

    protected HttpHeaders createHeaders(ContentType contentType) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + TOKEN);
        headers.add("Content-type", contentType.toString());
        return headers;
    }
}
