package ru.yandex.webmaster3.viewer.http.indexing2.urls;

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

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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.checklist.data.SiteProblemTypeEnum;
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.storage.checklist.dao.ChecklistPageSamplesService;
import ru.yandex.webmaster3.storage.checklist.dao.ChecklistSamplesType;
import ru.yandex.webmaster3.storage.checklist.data.AbstractProblemInfo;
import ru.yandex.webmaster3.storage.checklist.service.SiteProblemsService;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.checklist.extras.PageSamplesRequest;

@Slf4j
@ReadAction
@Description("Получить примеры для алерта обхода robots.txt")
@Category("checklist")
@Component("/checklist/extras/disallowedUrlsSamples")
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
public class DisallowedUrlsSamplesAction extends AbstractUserVerifiedHostAction<PageSamplesRequest,
        DisallowedUrlsSamplesResponse> {
    private final SiteProblemsService siteProblemsService;
    private final ChecklistPageSamplesService checklistPageSamplesService;

    private final SiteProblemTypeEnum problemType = SiteProblemTypeEnum.DISALLOWED_URLS_ALERT;

    @Override
    public DisallowedUrlsSamplesResponse process(PageSamplesRequest request) {
        AbstractProblemInfo problemInfo = siteProblemsService.getRealTimeProblemInfo(request.getHostId(), problemType);

        if (problemInfo == null || problemInfo.getContent() == null || problemInfo.getState() == problemType.getDefaultState()) {
            return new DisallowedUrlsSamplesResponse(Collections.emptyList(), 0);
        }

        PageUtils.Pager pager = PageUtils.getPage(request.getP(), request.getPSize());
        final ChecklistSamplesType checklistSamplesType = ChecklistSamplesType.byProblemType(problemType);
        List<String> examples = checklistPageSamplesService.getSamples(request.getHostId(), checklistSamplesType);
        log.info("Examples: {}", examples.toString());

        List<String> samples = examples.stream()
                .skip(pager.toRangeStart())
                .limit(pager.getPageSize())
                .collect(Collectors.toList());

        log.info("Samples: {}", samples);
        return new DisallowedUrlsSamplesResponse(samples, examples.size());
    }


}
