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

import java.util.List;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import org.joda.time.LocalDate;
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.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.request.PagerAware;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.feeds.statistics.FeedsEnrichedShowsCHDao;
import ru.yandex.webmaster3.storage.feeds.statistics.UrlShows;
import ru.yandex.webmaster3.storage.searchquery.importing.dao.YtClickhouseDataLoadRepository;
import ru.yandex.webmaster3.storage.ytimport.YtClickhouseDataLoadType;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.viewer.http.feeds.statistics.GetFeedsEnrichedShowsStatisticsAction.Request;
import ru.yandex.webmaster3.viewer.http.feeds.statistics.GetFeedsEnrichedShowsStatisticsAction.Response;

/**
 * Created by Oleg Bazdyrev on 30/03/2022.
 */
@ReadAction
@Category("feeds")
@Component("/feeds/enrichedShows")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetFeedsEnrichedShowsStatisticsAction extends AbstractUserVerifiedHostAction<Request, Response> {

    private final YtClickhouseDataLoadRepository ytClickhouseDataLoadRepository;
    private final FeedsEnrichedShowsCHDao feedsEnrichedShowsCHDao;

    @Override
    public Response process(Request request) {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        LocalDate to = ytClickhouseDataLoadRepository.load(YtClickhouseDataLoadType.FEEDS_ENRICHED_SHOWS).getMaxProcessedDate();
        var urls = feedsEnrichedShowsCHDao.getTopShows(domain, request.type, to.minusDays(7), to, request.p, request.pSize);
        return new Response(urls);
    }

    public static final class Request extends AbstractUserVerifiedHostRequest implements PagerAware {
        @Setter(onMethod_ = @RequestQueryProperty)
        private int p = 0;
        @Setter(onMethod_ = @RequestQueryProperty)
        private int pSize = 20;
        @Setter(onMethod_ = @RequestQueryProperty(required = true))
        private NativeFeedType type;
    }

    @Value
    public static class Response implements ActionResponse.NormalResponse {
        List<UrlShows> urls;
    }
}
