package com.inspect.partrolresult.service;

import com.alibaba.fastjson.JSONObject;
import com.inspect.analysis.constant.AnalyseConstants;
import com.inspect.analysis.utils.SimpleHttpClient;
import com.inspect.partrolresult.domain.AnalyseRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.retry.RetryContext;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.retry.support.RetrySynchronizationManager;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class AnalyseRequestRetryableDelegate {

    @Retryable(
            value = IOException.class,
            maxAttempts = 5,
            backoff = @Backoff(delay = 2000, multiplier = 1.0))
    public boolean callRemoteAnalyseService(final AnalyseRequest analyseReq) throws IOException {
        RetryContext retryContext = RetrySynchronizationManager.getContext();
        int retryCount = retryContext != null ? retryContext.getRetryCount() : 0;
        log.info("CALL_REMOTE_ANALYZE taskPatrolId: {}, retryCount: {}, requestId: {}, isFilter: {}, URL: {}, PARAMS: {}",
                analyseReq.getTaskPatrolId(),
                retryCount,
                analyseReq.getRequestId(),
                analyseReq.isFilter(),
                analyseReq.getRequestUrl(),
                analyseReq);
        String result = SimpleHttpClient.doPostJson(analyseReq.getRequestUrl(), analyseReq.toString());
        log.info("CALL_REMOTE_ANALYZE RESULT: {}",  result);
        if (!"200".equals(JSONObject.parseObject(result).getString(AnalyseConstants.ANALYSE_CODE))) {
            log.info("CALL_REMOTE_ANALYZE FAIL: {}", JSONObject.parseObject(result).getString(AnalyseConstants.ANALYSE_CODE));
            return false;
        }

        return true;
    }

    @SuppressWarnings("unused")
    @Recover
    public boolean recover(IOException e, final AnalyseRequest analyseReq) {
        log.info("CALL_REMOTE_ANALYZE RECOVER: taskPatrolId: {}, retryCount: {}, requestId: {}",
                analyseReq.getTaskPatrolId(),
                analyseReq.getRetryCount(),
                analyseReq.getRequestId());
        return false;
    }
}
