package ru.yandex.webmaster3.monitoring.solomon.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;
import ru.yandex.solomon_api.api.AlertingApi;
import ru.yandex.solomon_api.model.*;
import ru.yandex.webmaster3.core.openapi.internal.ApiClient;
import ru.yandex.webmaster3.core.openapi.internal.ApiException;

import java.util.List;

/**
 * Created by Oleg Bazdyrev on 21/07/2017.
 */
public class SolomonControlApiV2Service {

    private static final Logger log = LoggerFactory.getLogger(SolomonControlApiV2Service.class);

    private final static int PAGE_SIZE_NO_PAGING = 1000; // считаем, что при таком размере ответ помещается на одну страницу
    private static final String SOLOMON_PROJECT = "webmaster";
    private ApiClient solomonAPIClient;
    private AlertingApi alertingApi;

    public void init() {
        alertingApi = new AlertingApi(solomonAPIClient);
    }

    public void deleteTrigger(String id) throws ApiException {
        alertingApi.deleteAlertUsingDELETE(SOLOMON_PROJECT, id);
    }

    public void createOrUpdate(SolomonAlert alert) throws ApiException {
        try {
            log.info("Syncing alert: {}", alert);

            SolomonAlert prevAlert = alertingApi.getAlertUsingGET(alert.getProjectId(), alert.getId());
            alertingApi.updateAlertUsingPUT(alert.getProjectId(), alert.getId(), alert.version(prevAlert.getVersion()));
        } catch (ApiException e) {
            if (e.getCode() == 404) {
                log.info("Alert {} doesn't exist, creating", alert.getId());
                alertingApi.createAlertUsingPOST(alert.getProjectId(), alert);
            } else {
                throw e;
            }
        }
    }

    public List<SolomonSubAlertListItemDto> listSubAlerts(String parentId, List<String> filterByEvaluationStatus, List<String> annotationKeys) throws ApiException {
        SolomonPagedResultDtoSubAlertListItemDto page = alertingApi.listSubAlertsByParentUsingGET(SOLOMON_PROJECT, parentId, filterByEvaluationStatus, annotationKeys, PAGE_SIZE_NO_PAGING, null);
        return page.getItems();
    }

    public SolomonAlertEvaluationState getAlertStatus(String alertId) throws ApiException {
        return alertingApi.getAlertStateUsingGET(SOLOMON_PROJECT, alertId);
    }

    @Required
    public void setSolomonAPIClient(ApiClient solomonAPIClient) {
        this.solomonAPIClient = solomonAPIClient;
    }
}
