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

import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;

import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.Value;
import org.apache.commons.lang3.tuple.Pair;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.feeds.feed.FeedsQualityErrorEnum;
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.metrics.Category;
import ru.yandex.webmaster3.core.util.W3Collectors;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.feeds.logs.FeedsOffersLogsHistoryCHDao;
import ru.yandex.webmaster3.storage.feeds.logs.FeedsOffersLogsHistoryCHDao.FeedRecord;
import ru.yandex.webmaster3.storage.feeds.logs.SerpdataLogsHistoryCHDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;

/**
 * Created by Oleg Bazdyrev on 19/01/2022.
 */
@ReadAction
@Category("feeds")
@Component("/feeds/domainErrors")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetFeedsDomainErrorsAction extends AbstractUserVerifiedHostAction<GetFeedsDomainErrorsAction.Request, GetFeedsDomainErrorsAction.Response> {

    private static final String EMPTY_FEED = "";

    private final SerpdataLogsHistoryCHDao serpdataLogsHistoryCHDao;

    @Override
    public Response process(Request request) {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        List<FeedRecord> lastStates = serpdataLogsHistoryCHDao.getLastState(domain, null, Collections.singleton(EMPTY_FEED));
        EnumMap<NativeFeedType, DomainErrors> errorsByType = lastStates.stream()
                .collect(W3Collectors.toEnumMap(feedRecord ->
                        NativeFeedType.fromCode(feedRecord.getType()), DomainErrors::fromFeedRecord, NativeFeedType.class));
        return new Response(errorsByType);
    }

    @Setter(onMethod_ = @RequestQueryProperty)
    public static final class Request extends AbstractUserVerifiedHostRequest {
        NativeFeedType feedType;
    }

    @Value
    public static final class Response implements ActionResponse.NormalResponse {
        EnumMap<NativeFeedType, DomainErrors> errorsByType;
    }

    @Value
    public static class DomainErrors {
        @Description("Временная метка (ее надо передавать ручку скачивания)")
        DateTime timestamp;
        long errorsCount;
        @Description("Ошибки, сгруппированные по типам")
        Map<FeedsQualityErrorEnum, List<FeedsOffersLogsHistoryCHDao.OfferErrorInfo>> errors;

        public static DomainErrors fromFeedRecord(FeedRecord feedRecord) {
            return new DomainErrors(feedRecord.getTimestamp(),
                    feedRecord.getErrorStats() == null ? 0L : feedRecord.getErrorStats().getError() + feedRecord.getErrorStats().getWarning(),
                    feedRecord.getErrors().entrySet().stream()
                    .map(pair -> Pair.of(FeedsQualityErrorEnum.byCode(pair.getKey()), pair.getValue()))
                    .collect(W3Collectors.toEnumMap(FeedsQualityErrorEnum.class))
            );
        }
    }

}
