package ru.yandex.webmaster3.viewer.http.turbo.feed;

import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.stream.Collectors;

import com.google.common.base.Strings;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.http.RequestQueryProperty;
import ru.yandex.webmaster3.core.http.WebmasterErrorResponse;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.turbo.model.TurboUrl;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedSettings;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedSettingsInfo;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedStatistics;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedStatisticsInfo;
import ru.yandex.webmaster3.core.turbo.model.feed.TurboFeedType;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.util.ydb.exception.WebmasterYdbException;
import ru.yandex.webmaster3.storage.turbo.service.TurboFeedsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.viewer.http.turbo.feed.GetTurboUrlsAction.Request;

/**
 * Created by Oleg Bazdyrev on 06/07/2017.
 */
@ReadAction
@Category("turbo")
@Description("Возвращает список превью турбо-страничек для заданного фида")
public class GetTurboUrlsAction extends AbstractUserVerifiedHostAction<Request, GetTurboUrlsResponse> {

    private static final String NCRND_PARAM = "&ncrnd=";

    private TurboFeedsService turboFeedsService;

    private String turboUrlSuffix;

    @Override
    public GetTurboUrlsResponse process(Request request) {
        // ищем фид
        try {
            TurboFeedSettingsInfo settings;
            TurboFeedStatisticsInfo statistics;
            if (!Strings.isNullOrEmpty(request.getFeedUrl())) {
                Pair<TurboFeedSettings, TurboFeedStatistics> pair =
                        turboFeedsService.getFeedWithStatistics(WwwUtil.cutWWWAndM(request.getHostId()), request.getFeedUrl());
                if (pair == null) {
                    throw new WebmasterException("Wrong feed url",
                            new WebmasterErrorResponse.IllegalParameterValueResponse(getClass(), "feedUrl", request.getFeedUrl()));
                }
                settings = pair.getLeft();
                statistics = pair.getRight();
            } else if (request.getTaskId() != null) {
                Pair<TurboFeedSettingsInfo, TurboFeedStatisticsInfo> pair =
                        turboFeedsService.getApiFeedStats(request.getHostId(), request.getTaskId());
                settings = pair == null ? null : pair.getLeft();
                statistics = pair == null ? null : pair.getRight();
            } else {
                throw new WebmasterException("Both feedUrl and taskId is empty",
                        new WebmasterErrorResponse.IllegalParameterValueResponse(getClass(), "feedUrl", null));
            }

            List<TurboUrl> turboUrls = null;
            if (statistics != null && statistics.getTurboUrls() != null) {
                Random random = new Random();
                // добвляем суффикс ко всем турбо-ссылкам
                turboUrls = statistics.getTurboUrls().stream()
                        .limit(10L)
                        .filter(turboUrl -> !Strings.isNullOrEmpty(turboUrl.getTurboUrl()) || turboUrl.isDeleted())
                        .map(turboUrl -> turboUrl.withTurboUrlSuffix(turboUrlSuffix + NCRND_PARAM + random.nextLong()))
                        .sorted(Comparator.comparing(TurboUrl::isDeleted))
                        .collect(Collectors.toList());
            }

            return new GetTurboUrlsResponse.NormalResponse(!settings.isActive(), turboUrls);
        } catch (WebmasterYdbException e) {
            throw new WebmasterException("Error reading feed stats from Cassandra",
                    new WebmasterErrorResponse.YDBErrorResponse(getClass(), e), e);
        }
    }

    public static class Request extends AbstractUserVerifiedHostRequest {

        private TurboFeedType feedType = TurboFeedType.RSS;
        private String feedUrl;
        private UUID taskId;

        public TurboFeedType getFeedType() {
            return feedType;
        }

        @Description("Тип фида (на будущее) по умолчанию RSS")
        @RequestQueryProperty
        public void setFeedType(TurboFeedType feedType) {
            this.feedType = feedType;
        }

        public String getFeedUrl() {
            return feedUrl;
        }

        @Description("Адрес фида")
        @RequestQueryProperty
        public void setFeedUrl(String feedUrl) {
            this.feedUrl = feedUrl;
        }

        public UUID getTaskId() {
            return taskId;
        }

        @Description("Идентификатор таски API")
        @RequestQueryProperty
        public void setTaskId(UUID taskId) {
            this.taskId = taskId;
        }
    }

    @Required
    public void setTurboFeedsService(TurboFeedsService turboFeedsService) {
        this.turboFeedsService = turboFeedsService;
    }

    @Required
    public void setTurboUrlSuffix(String turboUrlSuffix) {
        this.turboUrlSuffix = turboUrlSuffix;
    }

}
