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

import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.turbo.model.statistics.TurboTopUrlInfo;
import ru.yandex.webmaster3.core.util.functional.ThrowingConsumer;
import ru.yandex.webmaster3.storage.download.common.MdsExportTaskData;
import ru.yandex.webmaster3.storage.download.common.TurboTopPagesWithoutTurboMdsExportDescriptor;
import ru.yandex.webmaster3.storage.turbo.service.TurboClickStatisticsService;
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 TopPagesWithoutTurboMdsDataProvider extends AbstractMdsDataProvider<TopPagesWithoutTurboCsvRow> {

    private final TurboClickStatisticsService turboClickStatisticsService;

    @Override
    public void provide(MdsExportTaskData exportTaskData, ThrowingConsumer<TopPagesWithoutTurboCsvRow, Exception> consumer) {
        var exportDescriptor = (TurboTopPagesWithoutTurboMdsExportDescriptor) exportTaskData.getDescriptor();
        String domain = exportDescriptor.getDomain();

        List<TurboTopUrlInfo> list = turboClickStatisticsService.topUrlsWithoutTurbo(domain);
        list
                .stream()
                .map(e -> new TopPagesWithoutTurboCsvRow(e.getUrl(), String.valueOf(e.getClicks())))
                .forEach(r -> rethrowingUnchecked(consumer).accept(r));

    }

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