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

import java.util.List;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.util.functional.ThrowingConsumer;
import ru.yandex.webmaster3.storage.download.common.MdsExportTaskData;
import ru.yandex.webmaster3.storage.feeds.download.FeedsEnrichedShowsMdsExportDescriptor;
import ru.yandex.webmaster3.storage.feeds.statistics.FeedsEnrichedShowsCHDao;
import ru.yandex.webmaster3.storage.feeds.statistics.UrlShows;
import ru.yandex.webmaster3.worker.download.AbstractMdsDataProvider;

import static ru.yandex.webmaster3.core.util.functional.ThrowingConsumer.rethrowingUnchecked;

/**
 * Created by Oleg Bazdyrev on 31/03/2022.
 */
@Service
@AllArgsConstructor(onConstructor_ = @Autowired)
public class FeedsEnrichedShowsMdsDataProvider extends AbstractMdsDataProvider<UrlShows> {

    private final FeedsEnrichedShowsCHDao feedsEnrichedShowsCHDao;

    @Override
    public void provide(MdsExportTaskData data, ThrowingConsumer<UrlShows, Exception> consumer) throws Exception {
        var desc = (FeedsEnrichedShowsMdsExportDescriptor) data.getDescriptor();
        List<UrlShows> topShows = feedsEnrichedShowsCHDao.getTopShows(desc.getDomain(), desc.getFeedType(), desc.getFrom(), desc.getTo(), 0, 10000);
        if (topShows.isEmpty()) {
            rethrowingUnchecked(consumer).accept(new UrlShows(null, 0));
        } else {
            for (var us : topShows) {
                rethrowingUnchecked(consumer).accept(us);
            }
        }
    }

    @Override
    public Class<UrlShows> getRowClass() {
        return UrlShows.class;
    }
}
