package com.inspect.job.task;

import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.job.domain.task.PatrolPresetPos;
import com.inspect.job.domain.task.PatrolPresetPosSlim;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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;
import java.net.URLEncoder;

@Component
public class IvsOperateRetryableDelegate {
    private static final Logger log = LoggerFactory.getLogger(IvsOperateRetryableDelegate.class);

    private String API_CONTROL_PRESET = "/api/v1/control/preset";

    @Value("${liveSIPB.url}")
    private String liveIVS_URL;

    public boolean setCameraToPreset(String uuid, PatrolPresetPosSlim presetPos) {
        try {
            final String url = liveIVS_URL + API_CONTROL_PRESET;
            final String param = "serial=" + presetPos.getVideoNvrCode()
                    + "&command=goto&preset=" + presetPos.getPresetPosCode()
                    + "&code=" + presetPos.getChannelCode()
                    + "&name=" + URLEncoder.encode(presetPos.getPresetPosName(), ("UTF-8"))
                    + "&id=" + presetPos.getPatrolPointId()
                    + "&host=" + presetPos.getHost()
                    + "&port=" + presetPos.getPort()
                    + "&username=" + presetPos.getUsername()
                    + "&password=" + presetPos.getPassword()
                    + "&address=" + presetPos.getAddress()
                    ;
            log.info("API_CONTROL_PRESET uuid: {}, param: {}, request: {}",
                    uuid,
                    presetPos.getPatrolPointId() + "-" + presetPos.getPresetPosName(),
                    url + "?" + param);
            HttpClientUtils.get(url, param);
            return true;
        } catch (Exception e) {
            log.info("API_CONTROL_PRESET FAIL: {}", e.getMessage());
            return false;
        }
    }

    @Retryable(
            value = IOException.class,
            maxAttempts = 5,
            backoff = @Backoff(delay = 2000, multiplier = 1.0))
    public boolean sendCameraPresetRequest(PatrolPresetPos presetPos) throws IOException {
        try {
            RetryContext retryContext = RetrySynchronizationManager.getContext();
            int retryCount = retryContext != null ? retryContext.getRetryCount() : 0;
            final String url = liveIVS_URL + API_CONTROL_PRESET;
            final String param = "serial=" + presetPos.getVideoNvrCode()
                    + "&command=goto&preset=" + presetPos.getPresetPosCode()
                    + "&code=" + presetPos.getChannelCode()
                    + "&name=" + presetPos.getPresetPosName()
                    + "&id=" + presetPos.getPatrolPointId();
            log.info("API_CONTROL_PRESET retryCount: {}, param: {}, request: {}",
                    retryCount,
                    presetPos.getPatrolPointId() + "-" + presetPos.getPresetPosName(),
                    url + "?" + param);
            HttpClientUtils.get(url, param);
            return true;
        } catch (Exception e) {
            log.info("API_CONTROL_PRESET RETRY FAIL: {}", e.getMessage());
            throw new IOException("API_CONTROL_PRESET FAIL: " + e.getMessage());
        }
    }

    @SuppressWarnings("unused")
    @Recover
    public boolean recover(IOException e, PatrolPresetPos presetPos) {
        log.info("API_CONTROL_PRESET RECOVER MSG: {}", e.getMessage());
        return false;
    }

}
