package enea.lecservice.services;

import enea.lecservice.models.dto.BaseRequest;
import enea.lecservice.models.dto.DataRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.security.sasl.AuthenticationException;
import java.util.HashMap;
import java.util.Map;

@Log4j2
@Service
@Profile("!dev")
@RequiredArgsConstructor
public class DataService implements IDataService {

    @Value("${data.api.baseurl}")
    private String baseUrl;

    @Override
    public String getListOfFunctions(BaseRequest request) {
        String url = baseUrl + "/data/getListOfFunctions";

        var headers = new org.springframework.http.HttpHeaders();
        headers.add(HttpHeaders.CONTENT_LANGUAGE, request.getContentLanguage());
        headers.add(HttpHeaders.AUTHORIZATION, request.getToken());

        var entity = new HttpEntity<>(headers);
        return new RestTemplate().postForObject(url, entity, String.class);
    }
    
    @Override
    public String clearListOfFunctions(BaseRequest request) {
        String url = baseUrl + "/data/clearListOfFunctions";

        var headers = new org.springframework.http.HttpHeaders();
        headers.add(HttpHeaders.CONTENT_LANGUAGE, request.getContentLanguage());
        headers.add(HttpHeaders.AUTHORIZATION, request.getToken());

        var entity = new HttpEntity<>(headers);
        return new RestTemplate().postForObject(url, entity, String.class);
    }

    @Override
    public String getData(DataRequest request, Integer index) {
        return getData(request);
    }

	@Override
	public String getData(DataRequest request) {
        String url = String.format("%s%s",
                baseUrl,
                "/data/getData"
        );
        var headers = new org.springframework.http.HttpHeaders();
        headers.add(HttpHeaders.CONTENT_LANGUAGE, request.getContentLanguage());
        headers.add(HttpHeaders.AUTHORIZATION, request.getToken());

        var map = new HashMap<String, Object>();
        map.put("queryid", Integer.parseInt(request.getQueryId()));
        for (var param : request.getParameters())
            map.put(param.getName(), param.getValue());

        var entity = new HttpEntity<>(map, headers);

        ResponseEntity<String> response = new RestTemplate().postForEntity(url, entity, String.class);
        if (response.getStatusCode().is4xxClientError()) {
            throw new AccessDeniedException("Serve data refused with 4xx error!");
        }

	    return response.getBody();
	}
}
