package ru.yandex.webmaster3.viewer.http.feeds.download;

import com.google.common.hash.Hasher;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.webmaster3.core.feeds.feed.NativeFeedType;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.download.common.MdsExportDescriptor;
import ru.yandex.webmaster3.storage.feeds.download.FeedsNotEnrichableShowsMdsExportDescriptor;
import ru.yandex.webmaster3.storage.searchquery.importing.dao.YtClickhouseDataLoadRepository;
import ru.yandex.webmaster3.storage.ytimport.YtClickhouseDataLoadType;
import ru.yandex.webmaster3.viewer.http.download.DownloadAction2;
import ru.yandex.webmaster3.viewer.http.download.DownloadRequest;

/**
 * Created by Oleg Bazdyrev on 31/03/2022.
 */
@ReadAction
@Category("feeds")
@Component("/feeds/downloadNotEnrichableShows")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DownloadFeedsNotEnrichableShowsAction extends DownloadAction2<DownloadFeedsNotEnrichableShowsAction.Request> {

    private static final DateTimeFormatter DAY_FORMAT = DateTimeFormat.forPattern("YYYYMMdd");

    private final YtClickhouseDataLoadRepository ytClickhouseDataLoadRepository;

    @Override
    protected MdsExportDescriptor makeRequest(Request request) {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        LocalDate to = ytClickhouseDataLoadRepository.load(YtClickhouseDataLoadType.FEEDS_NOT_ENRICHABLE_SHOWS).getMaxProcessedDate();
        return new FeedsNotEnrichableShowsMdsExportDescriptor(domain, request.type, to.minusDays(7), to);
    }

    @Override
    protected String generateFileName(Request request, long hash) {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        LocalDate to = ytClickhouseDataLoadRepository.load(YtClickhouseDataLoadType.FEEDS_NOT_ENRICHABLE_SHOWS).getMaxProcessedDate();
        return "shows-not-enrichable-" + domain + "-" + request.type + "_" + to.minusDays(7).toString(DAY_FORMAT) + "-" + to.toString(DAY_FORMAT);
    }

    @Override
    protected void customizeHash(Hasher h, Request request) {
        h.putBytes(getClass().getName().getBytes());
        h.putLong(request.type.value());
    }

    @Setter(onMethod_ = @RequestQueryProperty(required = true))
    public static final class Request extends DownloadRequest<FeedsOffersErrorsExportField, FeedOffersErrorsExportFilter> {
        NativeFeedType type;
    }
}
