package com.sonic.lion.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Component
public class NetRetryUtils {

    @Autowired
    private RestTemplate restTemplate;

    @Retryable(value = RestClientException.class, maxAttempts = 5,
            backoff = @Backoff(delay = 5000L, multiplier = 1.5))
    public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables) {
        return restTemplate.postForObject(url, request, responseType, uriVariables);
    }

    @Retryable(value = RestClientException.class, maxAttempts = 5,
            backoff = @Backoff(delay = 5000L, multiplier = 1.5))
    public String getForObject(String url,   String authorization) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + authorization);
        HttpEntity<Object> requestEntity = new HttpEntity<Object>( headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
        return response.getBody();
    }

    @Retryable(value = RestClientException.class, maxAttempts = 5,
            backoff = @Backoff(delay = 5000L, multiplier = 1.5))
    public String putForObject(String url, @Nullable Object request, String authorization) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "Bearer " + authorization);
        HttpEntity<Object> requestEntity = new HttpEntity<Object>(request, headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
        log.info("===> putForObject response : {}", response);
        return response.getBody();
    }

}
