package ru.yandex.webmaster3.viewer.http.hoststat;

import lombok.RequiredArgsConstructor;
import lombok.Value;
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.hoststat.HostStatistics;
import ru.yandex.webmaster3.core.hoststat.HostStatistics.ContentAttrSample;
import ru.yandex.webmaster3.core.hoststat.HostStatistics.PageSample;
import ru.yandex.webmaster3.core.http.ActionResponse;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.hoststat.HostStatisticsInfo;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.hoststat.HostStatisticsCHDao;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostRequest;
import ru.yandex.webmaster3.viewer.http.hoststat.GetHostContentStatisticsAction.Request;
import ru.yandex.webmaster3.viewer.http.hoststat.GetHostContentStatisticsAction.Response;

/**
 * Created by Oleg Bazdyrev on 12/03/2021.
 */
@Category("checklist")
@ReadAction
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@Component("/checklist/hostContentStatistics")
public class GetHostContentStatisticsAction extends AbstractUserVerifiedHostAction<Request, Response> {

    private final HostStatisticsCHDao hostStatisticsCHDao;

    @Override
    public Response process(Request request) {
        HostStatistics statistics = hostStatisticsCHDao.getHostStatisticsWithSamples(request.getHostId());
        // some sorting
        if (statistics != null) {
            statistics.getSlowPageSamples().sort(PageSample.BY_LAST_ACCESS_DESC);
            statistics.getEmptyTitleSamples().sort(PageSample.BY_LAST_ACCESS_DESC);
            statistics.getEmptyDescriptionSamples().sort(PageSample.BY_LAST_ACCESS_DESC);
            statistics.getPrevailingTitles().sort(ContentAttrSample.BY_COUNT_DESC);
            statistics.getPrevailingDescriptions().sort(ContentAttrSample.BY_COUNT_DESC);
            statistics.getPrevailingTitles().forEach(s -> s.getPageSamples().sort(PageSample.BY_LAST_ACCESS_DESC));
            statistics.getPrevailingDescriptions().forEach(s -> s.getPageSamples().sort(PageSample.BY_LAST_ACCESS_DESC));
        }

        return new Response(HostStatisticsInfo.fromHostStatistics(statistics));
    }

    public static final class Request extends AbstractUserVerifiedHostRequest {

    }

    @Value
    public static final class Response implements ActionResponse.NormalResponse {
        @Description("Общая статистика по хосту")
        HostStatisticsInfo hostStatistics;
    }
}
