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

import java.util.List;

import org.joda.time.Instant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Required;

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.urls.DownloadEventUrlsTaskData;
import ru.yandex.webmaster3.storage.searchurl.download.DownloadSearchEventService;
import ru.yandex.webmaster3.storage.searchurl.download.EventUrlCsvRow;
import ru.yandex.webmaster3.worker.ProcessingCountLimitedTask;
import ru.yandex.webmaster3.worker.download.DownloadRunnerService;

/**
 * Created by ifilippov5 on 13.02.17.
 */
@Category("searchurl")
public class DownloadEventUrlsTask extends ProcessingCountLimitedTask<DownloadEventUrlsTaskData> {
    private static final Logger log = LoggerFactory.getLogger(DownloadEventUrlsTask.class);
    private DownloadSearchEventService downloadSearchEventService;
    private DownloadRunnerService downloadRunnerService;
    private DownloadInfoYDao downloadInfoYDao;

    @Override
    public Result run(DownloadEventUrlsTaskData data) {
        List<EventUrlCsvRow> samples;
        try {
            samples = downloadSearchEventService.getSamples(data.getHostId(), data.getParameterFilters(),
                    data.getNodeId());
        } catch (Exception e) {
            log.error("Download task with hostId = {} and hash = {} terminate in status Internal Error through " +
                            "exception during get data",
                    data.getHostId(), data.getHash(), e);
            downloadInfoYDao.add(data.getHostId(), data.getHash(), DownloadInfo.error());
            throw e;
        }
        downloadRunnerService.run(data, samples);
        return new Result(TaskResult.SUCCESS);
    }

    @Required
    public void setDownloadSearchEventService(DownloadSearchEventService downloadSearchEventService) {
        this.downloadSearchEventService = downloadSearchEventService;
    }

    @Required
    public void setDownloadRunnerService(DownloadRunnerService downloadRunnerService) {
        this.downloadRunnerService = downloadRunnerService;
    }

    @Required
    public void setDownloadInfoYDao(DownloadInfoYDao downloadInfoYDao) {
        this.downloadInfoYDao = downloadInfoYDao;
    }

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