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 lombok.extern.slf4j.Slf4j;
import retrofit2.Call;
import retrofit2.Response;

import java.io.IOException;

@Slf4j
public abstract class AbstractRetrofitManager {

    protected final ObjectMapper objectMapper;

    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;
        }
    }

}
