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

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

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.MDSService;
import ru.yandex.webmaster3.storage.download.searchquery.AbstractDownloadQueryStatisticTaskData;

/**
 * Created by ifilippov5 on 03.03.17.
 */
public class DownloadStatisticRunnerService {
    private static final Logger log = LoggerFactory.getLogger(DownloadStatisticRunnerService.class);
    private DownloadInfoYDao downloadInfoYDao;
    private MDSService mdsService;

    public void run(AbstractDownloadQueryStatisticTaskData data, byte[] statistics) {
        Long hash = data.getHash();
        String uri = null;
        try {
            log.debug("Send data with {} length", statistics.length);
            uri = mdsService.uploadFileAndGetDownloadLink(statistics,
                    data.getFileName() + data.getExportFormat().getExtension());
        } catch (Exception e) {
            log.error("Unable to upload to MDS", e);
            log.debug("Write info about internal_error task status");
            downloadInfoYDao.add(data.getHostId(), hash, DownloadInfo.error());
        }

        log.debug("Write info about done task status");
        downloadInfoYDao.add(data.getHostId(), hash, DownloadInfo.success(data.getFileName(), uri));
    }

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

    @Required
    public void setMdsService(MDSService mdsService) {
        this.mdsService = mdsService;
    }
}
