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

import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.searchquery.OrderDirection;
import ru.yandex.webmaster3.core.util.functional.ThrowingConsumer;
import ru.yandex.webmaster3.storage.download.common.MdsExportTaskData;
import ru.yandex.webmaster3.storage.niche.NicheQueriesCHDao;
import ru.yandex.webmaster3.storage.niche.download.NicheQueriesMdsExportDescriptor;
import ru.yandex.webmaster3.worker.download.AbstractMdsDataProvider;

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

/**
 * ishalaru
 * 27.03.2020
 **/
@Slf4j
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component
public class NicheQueriesMdsDataProvider extends AbstractMdsDataProvider<NicheQueriesCsvRow> {

    public final NicheQueriesCHDao nicheQueriesCHDao;

    @Override
    public void provide(MdsExportTaskData data, ThrowingConsumer<NicheQueriesCsvRow, Exception> consumer) throws Exception {
        NicheQueriesMdsExportDescriptor ed = (NicheQueriesMdsExportDescriptor) data.getDescriptor();
        List<Pair<String, Long>> queries = nicheQueriesCHDao.getQueries(ed.getHostId(), ed.getDateFrom().toLocalDate(), ed.getDateTo().toLocalDate(),
                ed.getRegionsId(), ed.getDeviceType(), ed.getSource(), NicheQueriesCHDao.SortField.COUNT, OrderDirection.DESC, 100000, 0);

        queries.stream().map(pair -> new NicheQueriesCsvRow(pair.getLeft(), pair.getRight())).forEach(r -> rethrowingUnchecked(consumer).accept(r));
    }

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