package com.fractalite.amad_ndc.services;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

import com.fractalite.mercure.data.model.bo.Order;
import com.fractalite.mercure.data.model.common.PersonType;
import com.fractalite.mercure.data.model.person.Person;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;


@Service
public class CrmService {

    private static final Logger LOG = LoggerFactory.getLogger(CrmService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${url.crm.criteria}")
    private String urlCriteria;

    @Value("${url.crm.order.number}")
    private String urlOrderByNumber;

    @Value("${url.crm.put.order}")
    private String urlCrmPutOrder;


    @Autowired
    CrmEndpoints crmEndpoints;

    public CrmService() {
    }

    public String postCustomer(Order order, String indexUrl) throws HttpStatusCodeException {
        String urlCrmBase = crmEndpoints.getCrmEndpoint(Integer.parseInt(indexUrl));

//        LOG.info("-- urlCrmBase --" + urlCrmBase);

        LOG.info("--- urlCrmBase " + urlCrmBase + " order " + order.toString());
        String postResponse = null;
        ResponseEntity<String> response = null;
        String path = "";

        LOG.info("-- HermesOrderToCrmOrder" + order.toString());
        if (order.getCustomer().getPersonType().equals(PersonType.LEGAL)) {
            path = urlCrmBase + "/legalpersons";
        } else {
            path = urlCrmBase + "/naturalpersons";
        }
        LOG.info("-- crm path post customer --" + path);

        HttpEntity<Person> post_request = new HttpEntity<>(order.getCustomer(), getHeaders());
        response = restTemplate.exchange(path, HttpMethod.POST, post_request, String.class);
        postResponse = response.getBody();
        return postResponse;
    }

    public HttpHeaders getHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        return headers;
    }

    public String putOrder(Order order, String indexUrl) throws HttpStatusCodeException, JsonProcessingException {

        LOG.info("================================ PUT ORDER CRM ================================");

        System.out.println("---- number --- " + order.getNumber());
        System.out.println("---- ref --- " + order.getRef());
        System.out.println("---- orderId --- " + order.getOrderId());

        if (order == null) {
            return null;
        }

        String urlCrmBase = crmEndpoints.getCrmEndpoint(Integer.parseInt(indexUrl));

        String path = urlCrmBase + urlCrmPutOrder + order.getOrderId();
        LOG.info("-- put order path --" + path);

        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        ObjectWriter writer = mapper.writer().withoutAttribute("cashManagement");
        String jsonString = writer.writeValueAsString(order);

        LOG.info("-- order jsonString --\n" + jsonString);

        HttpEntity<String> put_request = new HttpEntity<>(jsonString, getHeaders());
        ResponseEntity<String> response = null;
        response = restTemplate.exchange(path, HttpMethod.PUT, put_request, String.class);

        LOG.info(String.valueOf(response.getStatusCode()));

        return response.getBody();
    }

    public Order getOrderById(String orderId, String indexUrl) throws HttpStatusCodeException, JsonProcessingException, ParseException {

        LOG.info("================================ GET ORDER BY ID CRM ================================");

        if (orderId == null || orderId.equals("")) {
            return null;
        }

        System.out.println("indexUrl"+indexUrl);
        String urlCrmBase = crmEndpoints.getCrmEndpoint(Integer.parseInt(indexUrl));
//        LOG.info("-- urlCrmBase : " + urlCrmBase);
//        LOG.info("-- orderId : " + orderId);

        ResponseEntity<Order> response = null;
        HttpEntity<String> get_request = new HttpEntity<>(getHeaders());
        String path = urlCrmBase + urlCrmPutOrder + orderId;
        LOG.info("-- GET order path : "+ path);


        response = restTemplate.exchange(path, HttpMethod.GET, get_request, Order.class);
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

//        LOG.info("-- order resp : "+ mapper.writeValueAsString(response.getBody()));

        return response.getBody();
    }

}
