package ru.yandex.webmaster3.viewer.http.checklist.extras;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
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.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.core.util.WwwUtil;
import ru.yandex.webmaster3.storage.turbo.dao.TurboDomainsStateCHDao;
import ru.yandex.webmaster3.storage.turbo.dao.TurboDomainsStateHelper;
import ru.yandex.webmaster3.storage.turbo.dao.commerce.model.TurboListingsInfo;
import ru.yandex.webmaster3.storage.turbo.dao.commerce.model.TurboListingsInfo.TurboAutoListingsError;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;

/**
 * Created by Oleg Bazdyrev on 2019-09-18.
 */
@ReadAction
@Description("Получение примеров ошибок листингов")
@Category("checklist")
@Component("/checklist/extras/turboListingErrorSamples")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class TurboListingErrorSamplesAction extends AbstractUserVerifiedHostAction<PageSamplesRequest, TurboListingErrorSamplesAction.Response> {

    private final TurboDomainsStateCHDao turboDomainsStateCHDao;

    @Override
    public Response process(PageSamplesRequest request) {
        String domain = WwwUtil.cutWWWAndM(request.getHostId());
        TurboListingsInfo info = turboDomainsStateCHDao.getDomainState(domain, TurboDomainsStateHelper.getListingInfoFields()).getListingsInfo();
        if (info == null) {
            return new Response(Collections.emptyList(), 0);
        }
        List<TurboAutoListingsError> allPublicErrors = info.getErrors().stream().filter(TurboAutoListingsError::isVisible).collect(Collectors.toList());
        PageUtils.Pager pager = PageUtils.getPage(request.getP(), request.getPSize());
        List<TurboAutoListingsError> errors = allPublicErrors.stream()
                .skip(pager.toRangeStart())
                .limit(pager.getPageSize()).collect(Collectors.toList());
        return new Response(errors, info.getErrors().size());
    }

    @Getter
    @RequiredArgsConstructor
    public class Response implements ActionResponse.NormalResponse {
        @Description("Примеры ошибок")
        private final List<TurboAutoListingsError> samples;
        @Description("Всего примеров")
        private final int totalSamples;
    }
}
