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

import lombok.RequiredArgsConstructor;
import org.joda.time.format.DateTimeFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.webmaster3.core.codes.YandexHttpStatusUtil;
import ru.yandex.webmaster3.core.data.HttpCodeInfo;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.worker.task.TaskResult;
import ru.yandex.webmaster3.storage.indexing2.download.DownloadIndexingUrlEventSamplesTaskData;
import ru.yandex.webmaster3.storage.indexing2.download.IndexedUrlEventSampleCsvRow;
import ru.yandex.webmaster3.storage.indexing2.samples.IndexingSamplesService;
import ru.yandex.webmaster3.storage.indexing2.samples.data.IndexedUrlEventSample;
import ru.yandex.webmaster3.worker.ProcessingCountLimitedTask;
import ru.yandex.webmaster3.worker.download.DownloadRunnerService;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * Created by ifilippov5 on 28.02.17.
 */
@Category("indexing")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DownloadIndexingUrlEventSamplesTask extends ProcessingCountLimitedTask<DownloadIndexingUrlEventSamplesTaskData> {

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

    private final IndexingSamplesService indexingSamplesService;
    private final DownloadRunnerService downloadRunnerService;

    @Override
    public Result run(DownloadIndexingUrlEventSamplesTaskData data) {
        downloadRunnerService.run(data, getSamples(data));

        return new Result(TaskResult.SUCCESS);
    }

    private List<IndexedUrlEventSampleCsvRow> getSamples(DownloadIndexingUrlEventSamplesTaskData data) {
        List<IndexedUrlEventSample> samples = indexingSamplesService.getEventSamples(data.getHostId(), data.getFilters(), data.getOrderBy(),
                data.getOrderDirection(), 0, (int) indexingSamplesService.getEventSamplesCount(data.getHostId(), data.getFilters()));

        return samples.stream()
                .map(sample -> new IndexedUrlEventSampleCsvRow(
                        sample.getUrl(),
                        Optional.of(sample).map(IndexedUrlEventSample::getCurrentCode).map(HttpCodeInfo::getStatus).flatMap(YandexHttpStatusUtil::yandexHttpStatus2View).orElse("0"),
                        Optional.of(sample).map(IndexedUrlEventSample::getPreviousCode).map(HttpCodeInfo::getStatus).flatMap(YandexHttpStatusUtil::yandexHttpStatus2View).orElse("0"),
                        Optional.of(sample).map(IndexedUrlEventSample::getLastAccess).map(date -> date.toString(DateTimeFormat.forPattern("dd.MM.yyyy"))).orElse("")
                ))
                .collect(Collectors.toList());
    }

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