package ru.yandex.webmaster3.monitoring.mirrors;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.datastax.driver.core.utils.UUIDs;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.scheduling.annotation.Scheduled;

import ru.yandex.webmaster3.core.solomon.HandleCommonMetricsService;
import ru.yandex.webmaster3.core.solomon.Indicators;
import ru.yandex.webmaster3.core.solomon.SolomonSensor;
import ru.yandex.webmaster3.storage.settings.dao.CommonDataStateYDao;

import static ru.yandex.webmaster3.storage.host.CommonDataType.MAIN_MIRRORS_DB;

/**
 * Created by Oleg Bazdyrev on 06/09/2017.
 */
public class MirrorsMonitoringService {

    private static final String SECTION_LABEL_VALUE = "mirrors";
    private static final int AVERAGE_SENSORS_SIZE = 300;

    private HandleCommonMetricsService handleCommonMetricsService;
    private CommonDataStateYDao commonDataStateYDao;

    private boolean enabled;
    private long refreshIntervalSeconds;

    @Scheduled(cron = "${webmaster3.monitoring.solomon.mirrors.refresh-cron}")
    private void push() throws Exception {
        if (!enabled) {
            return;
        }

        long now = System.currentTimeMillis();
        List<SolomonSensor> sensors = new ArrayList<>();

        // пока есть только один сенсор - возраст поколения зеркал
        UUID currentGenerationId = UUID.fromString(commonDataStateYDao.getValue(MAIN_MIRRORS_DB).getValue());
        long generationTimestamp = UUIDs.unixTimestamp(currentGenerationId);

        sensors.add(SolomonSensor.createAligned(refreshIntervalSeconds, (now - generationTimestamp) / 1000L)
                .withLabel(SolomonSensor.LABEL_SECTION, SECTION_LABEL_VALUE)
                .withLabel(SolomonSensor.LABEL_INDICATOR, Indicators.DATA_AGE));

        handleCommonMetricsService.handle(sensors, AVERAGE_SENSORS_SIZE);
    }

    @Required
    public void setHandleCommonMetricsService(HandleCommonMetricsService handleCommonMetricsService) {
        this.handleCommonMetricsService = handleCommonMetricsService;
    }

    @Required
    public void setCommonDataStateYDao(CommonDataStateYDao commonDataStateYDao) {
        this.commonDataStateYDao = commonDataStateYDao;
    }

    @Required
    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Required
    public void setRefreshIntervalSeconds(long refreshIntervalSeconds) {
        this.refreshIntervalSeconds = refreshIntervalSeconds;
    }
}
