package de.hftstuttgart.utils;

import de.hftstuttgart.config.ModocotProperties;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RestCall {

    private static final Logger LOG = LogManager.getLogger(RestCall.class);

    private final ModocotProperties modocotProperties;

    public RestCall(ModocotProperties modocotProperties) {
        this.modocotProperties = modocotProperties;
    }

    public <T> ResponseEntity<T> exchange(String specificUrl, HttpMethod method, T body, Class<T> responseType, Object... uriVariables) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_XML);
        headers.add("Authorization", "Basic " + new String(Base64.encodeBase64((this.modocotProperties.getJenkinsApiToken()).getBytes())));
        headers.add("user", "admin");
        LOG.info(method.toString() + ", to: " + this.modocotProperties.getJenkinsBaseUrl() + specificUrl);
        return restTemplate.exchange(this.modocotProperties.getJenkinsBaseUrl() + specificUrl, method, new HttpEntity<>(body, headers), responseType, uriVariables);
    }
}
