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

import java.util.List;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import ru.yandex.webmaster3.core.feeds.feed.FeedsOfferBanInfo;
import ru.yandex.webmaster3.core.util.functional.ThrowingConsumer;
import ru.yandex.webmaster3.storage.download.common.MdsExportTaskData;
import ru.yandex.webmaster3.storage.feeds.FeedsOfferBansYDao;
import ru.yandex.webmaster3.storage.feeds.download.FeedsOfferBansDescriptor;
import ru.yandex.webmaster3.worker.download.AbstractMdsDataProvider;

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

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FeedsOfferBansProvider extends AbstractMdsDataProvider<FeedsOfferBansCsvRow> {

    private final FeedsOfferBansYDao feedsOfferBansYDao;

    @Override
    public void provide(MdsExportTaskData exportTaskData, ThrowingConsumer<FeedsOfferBansCsvRow, Exception> consumer) throws Exception {
        var descriptor = (FeedsOfferBansDescriptor) exportTaskData.getDescriptor();


        List<FeedsOfferBanInfo> offerBans = feedsOfferBansYDao.list(descriptor.getDomain(), descriptor.getFeedType());
        if (offerBans.isEmpty()) {
            rethrowingUnchecked(consumer).accept(new FeedsOfferBansCsvRow(null, null, null, null, null, null));
        } else {
            offerBans.forEach(row -> {
                FeedsOfferBansCsvRow csvRow = new FeedsOfferBansCsvRow(row.getDomain(), row.getUrl(),
                        row.getOfferId(), new DateTime(row.getBanTimestamp().getMillis()).toString(), row.getBanReason().getDescription(), row.getComment());
                rethrowingUnchecked(consumer).accept(csvRow);
            });
        }
    }

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


    @lombok.Value
    public static class FeedsOfferBanData {

        @JsonProperty("domain")
        String domain;
        @JsonProperty("feed_url")
        String feedUrl;
        @JsonProperty("offer_id")
        String offerId;
        @JsonProperty("ts")
        long timestamp;
        @JsonProperty("reason")
        String reason;
        @JsonProperty("comment")
        String comment;

    }


}
