package com.cnooc.expert.external.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;
import java.util.Map;

@Slf4j
public abstract class AbstractRetrofitManager {

    protected final ObjectMapper objectMapper;

    private static final String ACCESS_KEY = "YsyhlUtP";

    public AbstractRetrofitManager() {
        objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    }

    // 结果检查
    protected <T> T getResponseBody(Call<T> call, String func) {
        log.info("{}", call.request());
        try {
            Response<T> response = call.execute();
            if (response.isSuccessful()) {
                log.debug("{}, code={}, message={}", func, response.code(), response.message());
                T body = response.body();
                log.info("{}", body);
                return body;
            } else {
                log.warn("{} not successful, code={}, message={}", func, response.code(), response.message());
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("{}, IOException, message={}", func, e.getMessage());
            return null;
        }
    }

    protected Map<String, Object> getHeaders() {
        Map<String, Object> headers = Maps.newHashMap();
        headers.put("Access_Key", ACCESS_KEY);
        return headers;
    }


}
