package ru.yandex.webmaster3.worker.download.searchquery;

import lombok.RequiredArgsConstructor;
import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.storage.download.DownloadInfo;
import ru.yandex.webmaster3.storage.download.DownloadInfoYDao;
import ru.yandex.webmaster3.storage.download.DownloadStatus;
import ru.yandex.webmaster3.storage.download.searchquery.DownloadUrlsIndicatorStatisticTaskData;
import ru.yandex.webmaster3.storage.download.searchquery.UrlsExportService;
import ru.yandex.webmaster3.worker.ProcessingCountLimitedTask;

/**
 * @author lester
 */
@Category("searchquery")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DownloadStatisticAllUrlsOneIndicatorTask extends ProcessingCountLimitedTask<DownloadUrlsIndicatorStatisticTaskData> {
    private static final Logger log = LoggerFactory.getLogger(DownloadStatisticAllUrlsOneIndicatorTask.class);
    private final DownloadStatisticRunnerService downloadStatisticRunnerService;
    private final UrlsExportService urlsExportService;
    private final DownloadInfoYDao downloadInfoYDao;

    @Override
    public Result run(DownloadUrlsIndicatorStatisticTaskData data) {
        byte[] statistics;
        try {
            statistics = urlsExportService.getAllUrlsIndicatorStatistics(
                    data.getHostId(),
                    data.getLocalDateFrom(),
                    data.getLocalDateTo(),
                    data.getRegionId(),
                    data.getRegionInclusion(),
                    data.getSpecialGroup(),
                    data.getIndicator(),
                    data.getDeviceType(),
                    data.getOrderByInd(),
                    data.getOrderDirectionInd(),
                    data.getPeriod(),
                    data.getExportFormat());
        } catch (Exception e) {
            log.error("Failed to get data from clickhouse", e);
            log.error("Download task with hostId = {} and hash = {} terminate in status Internal Error through " +
                            "exception during get data",
                    data.getHostId(), data.getHash());
            downloadInfoYDao.add(data.getHostId(), data.getHash(), DownloadInfo.error());
            throw new WebmasterException("Failed to get data",
                    new WebmasterErrorResponse.ClickhouseErrorResponse(getClass(), null, e), e);
        }

        downloadStatisticRunnerService.run(data, statistics);

        return new Result(TaskResult.SUCCESS);
    }

    @Override
    public Class<DownloadUrlsIndicatorStatisticTaskData> getDataClass() {
        return DownloadUrlsIndicatorStatisticTaskData.class;
    }
}
