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.util.WwwUtil;
import ru.yandex.webmaster3.storage.AbstractFilter;
import ru.yandex.webmaster3.storage.download.common.MdsExportDescriptor;
import ru.yandex.webmaster3.storage.feeds.download.FeedsClickStatisticsMdsExportDescriptor.FeedsOfferClickStatisticsMdsExportDescriptor;
import ru.yandex.webmaster3.storage.host.CommonDataType;
import ru.yandex.webmaster3.storage.settings.SettingsService;
import ru.yandex.webmaster3.viewer.http.download.DownloadAction2;
import ru.yandex.webmaster3.viewer.http.download.DownloadRequest;

/**
 * Created by Oleg Bazdyrev on 14/03/2022.
 */
@ReadAction
@Component("/feeds/download/offerClickStatistics")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class DownloadFeedsOfferClickStatisticsAction extends DownloadAction2<DownloadFeedsOfferClickStatisticsAction.Request> {

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

    private final SettingsService settingsService;

    @Override
    protected MdsExportDescriptor makeRequest(Request request) {
        LocalDate to = LocalDate.parse(settingsService.getSettingCached(CommonDataType.LAST_PROCESSED_USER_SESSIONS_FEEDS).getValue());
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        return new FeedsOfferClickStatisticsMdsExportDescriptor(domain, request.type, to.minusDays(7), to);
    }

    @Override
    protected String generateFileName(Request request, long hash) {
        LocalDate to = LocalDate.parse(settingsService.getSettingCached(CommonDataType.LAST_PROCESSED_USER_SESSIONS_FEEDS).getValue());
        return "shows&clicks-offers-" + WwwUtil.cutWWWAndM(request.getHostId()) + "_" + to.minusDays(7).toString(DAY_FORMAT) + "-" + to.toString(DAY_FORMAT);
    }

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

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

    public enum StubEnum {

    }

    public class StubExportFilter extends AbstractFilter<StubEnum> {
        public StubExportFilter(StubEnum indicator, Operation operation, String value) {
            super(indicator, operation, value);
        }
    }
}
