package ru.yandex.webmaster3.monitoring.searchurl;

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

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import ru.yandex.webmaster3.core.searchbase.SearchBaseUpdateInfo;
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.searchbase.dao.SearchBaseUpdatesYDao;
import ru.yandex.webmaster3.storage.searchurl.offline.dao.SearchBaseImportTablesYDao;
import ru.yandex.webmaster3.storage.searchurl.offline.data.SearchBaseImportInfo;
import ru.yandex.webmaster3.storage.searchurl.offline.data.SearchBaseImportTaskType;

/**
 * Мониторинг для страниц в поиске
 * Created by Oleg Bazdyrev on 18/07/2017.
 *
 * @see WMC-4278
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class SearchUrlSamplesMonitoringService {

    private static final Logger log = LoggerFactory.getLogger(SearchUrlSamplesMonitoringService.class);
    private static final String SECTION_LABEL_VALUE = "searchurl";
    private static final String LABEL_STATE = "state";
    private static final String NO_ACTUAL_BASE_STATE = "no_actual_base_state";
    private static final int AVERAGE_SENSORS_SIZE = 400;

    @Setter
    private HandleCommonMetricsService handleCommonMetricsService;
    @Setter
    private SearchBaseUpdatesYDao searchBaseUpdatesYDao; // кэш MonSearchBaseUpdatesService в мониторинге вряд ли нужен
    @Setter
    private SearchBaseImportTablesYDao searchBaseImportTablesYDao;
    @Setter
    private boolean enabled;
    @Setter
    private long refreshIntervalSeconds;
    @Setter
    private SearchBaseImportTaskType importTaskType;

    @Scheduled(cron = "${webmaster3.monitoring.solomon.searchurl.refresh-cron}")
    private void push() throws Exception {
        if (!enabled) {
            log.warn("Search urls import monitoring service disabled");
            return;
        }

        // найдем текующую дату и вычислим предположительную дату переключения на нее
        final SearchBaseUpdateInfo value = searchBaseUpdatesYDao.getUpdatesHistory().lastEntry().getValue();

        long timeAfterSwitchBase = Math.max(System.currentTimeMillis() - value.getBaseSwitchDate().getMillis(), 0L);

        SearchBaseImportInfo currImportInfo = searchBaseImportTablesYDao.getBaseInfo(importTaskType, value.getBaseCollectionDate());
        long nonActualBaseAge = 0;

        if (currImportInfo == null) {
            nonActualBaseAge = timeAfterSwitchBase;
        }

        String dataType = importTaskType.name().toLowerCase();

        List<SolomonSensor> sensors = new ArrayList<>();
        sensors.add(SolomonSensor.createAligned(refreshIntervalSeconds, nonActualBaseAge / 1000)
                .withLabel(SolomonSensor.LABEL_SECTION, SECTION_LABEL_VALUE)
                .withLabel(SolomonSensor.LABEL_DATA_TYPE, dataType)
                .withLabel(LABEL_STATE, NO_ACTUAL_BASE_STATE)
                .withLabel(SolomonSensor.LABEL_INDICATOR, Indicators.DATA_AGE));

        handleCommonMetricsService.handle(sensors, AVERAGE_SENSORS_SIZE);
    }
}
