package com.arms.api.util.alm;

import com.arms.api.util.errors.ErrorLogUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.taskadapter.redmineapi.RedmineException;
import com.taskadapter.redmineapi.RedmineManager;
import com.taskadapter.redmineapi.RedmineManagerFactory;
import com.taskadapter.redmineapi.bean.User;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.Optional;

@Component
public class RedmineUtil {

    public RedmineManager createRedmineOnPremiseCommunicator(String uri, String apiKey) {
        return RedmineManagerFactory.createWithApiKey(uri, apiKey);
    }

    public static WebClient createRedmineWebClientCommunicator(String uri, String apiToken) {

        return WebClient.builder()
                .baseUrl(uri)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
                .defaultHeader("X-Redmine-API-Key", apiToken)
                .build();
    }

    public String checkServerInfoPath(String serverInfoPath) {
        return serverInfoPath.endsWith("/") ? serverInfoPath.substring(0, serverInfoPath.length() - 1) : serverInfoPath;
    }

    public User getUserInfo(RedmineManager redmineManager, String userId) {

        User userInfo = null;
        try {
            userInfo = redmineManager.getUserManager().getUserById(Integer.valueOf(userId));
        } catch (RedmineException e) {
            ErrorLogUtil.exceptionLogging(e, this.getClass().getName(), userId + " 사용자정보 조회 오류");
        }

        return userInfo;
    }

    public <T> Mono<T> get(WebClient webClient, String uri, Class<T> responseType) {

        return webClient.get()
                .uri(uri)
                .retrieve()
                .bodyToMono(responseType);
    }

    public Optional<String> toJson(Object object) {
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();

        try {
            String json = gson.toJson(object);
            return Optional.of(json);
        } catch (Exception e) {
            ErrorLogUtil.exceptionLogging(e, this.getClass().getName(), "JSON 변환 실패");
            return Optional.empty();
        }
    }
}
