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

import org.springframework.beans.factory.annotation.Autowired;
import ru.yandex.webmaster3.core.util.functional.ThrowingConsumer;
import ru.yandex.webmaster3.storage.download.common.MdsExportTaskData;
import ru.yandex.webmaster3.storage.download.common.MetrikaCrawlSamplesMdsExportDescriptor;
import ru.yandex.webmaster3.storage.metrika.MetrikaCrawlSamplesService;
import ru.yandex.webmaster3.storage.metrika.dao.MetrikaCrawlSampleCondition;
import ru.yandex.webmaster3.storage.metrika.data.MetrikaCrawlSample;
import ru.yandex.webmaster3.storage.util.clickhouse2.condition.Condition;
import ru.yandex.webmaster3.worker.download.AbstractMdsDataProvider;

import java.util.List;

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

/**
 * @author leonidrom
 */
public class MetrikaCrawlSamplesMdsDataProvider extends AbstractMdsDataProvider<MetrikaCrawlSamplesSpreadsheetRow> {
    private final MetrikaCrawlSamplesService metrikaCrawlSamplesService;

    @Autowired
    public MetrikaCrawlSamplesMdsDataProvider(MetrikaCrawlSamplesService metrikaCrawlSamplesService) {
        this.metrikaCrawlSamplesService = metrikaCrawlSamplesService;
    }

    @Override
    public void provide(MdsExportTaskData exportTaskData, ThrowingConsumer<MetrikaCrawlSamplesSpreadsheetRow, Exception> consumer) throws Exception {
        var exportDescriptor = (MetrikaCrawlSamplesMdsExportDescriptor)exportTaskData.getDescriptor();
        var condition = MetrikaCrawlSampleCondition.makeCondition(exportDescriptor.getFilters());
        var samples = metrikaCrawlSamplesService.getSamples(exportDescriptor.getDomain(), exportDescriptor.getCounterId(), condition);
        samples.stream()
                .map(MetrikaCrawlSamplesSpreadsheetRow::fromMetrikaCrawlSample)
                .forEach(r -> rethrowingUnchecked(consumer).accept(r));
    }

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