package ru.yandex.webmaster3.api.host.action;

import java.util.Map;
import java.util.stream.Collectors;

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.api.http.auth.ActionPermission;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.core.checklist.data.SiteProblemSeverityEnum;
import ru.yandex.webmaster3.core.codes.ErrorGroupEnum;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.sitestructure.NewSiteStructure;
import ru.yandex.webmaster3.core.sitestructure.NewSiteStructureNode;
import ru.yandex.webmaster3.storage.checklist.service.SiteProblemsService;
import ru.yandex.webmaster3.storage.iks.IksService;
import ru.yandex.webmaster3.storage.sitestructure.SiteStructureService;

/**
 * @author avhaliullin
 */
@Description("Получить сводную информацию о сайте (a.k.a. 'Статистика сайта')")
@Category("host")
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@ActionPermission(Permission.COMMON)
public class GetHostSummaryAction extends AbstractApiAction<GetHostSummaryRequest, GetHostSummaryResponse> {

    private final SiteStructureService siteStructureService;
    private final SiteProblemsService siteProblemsService;
    private final IksService iksService;

    @Override
    public GetHostSummaryResponse process(GetHostSummaryRequest request) {
        NewSiteStructureNode rootNode = siteStructureService.getNode(request.getHostId(), NewSiteStructure.ROOT_NODE_ID);
        long excluded = rootNode.getHttpCodes().entrySet().stream()
                .filter(p -> ErrorGroupEnum.get(p.getKey()).isPresent())
                .mapToLong(Map.Entry::getValue).sum();
        long searchable = rootNode.getSearchDocCount();
        Map<SiteProblemSeverityEnum, Integer> siteProblems =
                siteProblemsService.listProblemsForHost(request.getHostId(), null)
                        .stream()
                        .filter(p -> p.getState().isPresent() && !p.getProblemType().isDisabled())
                        .collect(Collectors.groupingBy(p -> p.getProblemType().getSeverity(), Collectors.reducing(0, e -> 1, Integer::sum)));
        int sqi = iksService.getIksValue(request.getHostId());
        return new GetHostSummaryResponse(sqi, excluded, searchable, siteProblems);
    }
}
