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

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Component;
import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.api.addurl.data.RecrawlRequestInfo;
import ru.yandex.webmaster3.api.http.auth.Permission;
import ru.yandex.webmaster3.api.http.rest.AbstractApiAction;
import ru.yandex.webmaster3.core.addurl.UrlForRecrawl;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.storage.addurl.AddUrlRequestsService;

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

/**
 * @author avhaliullin
 */
@Description("Список задач на переобход")
@Category("addurl")
@Component
public class ListRecrawlRequestsAction extends AbstractApiAction<ListRecrawlRequestsRequest, ListRecrawlRequestsResponse> {
    private AddUrlRequestsService addUrlRequestsService;

    public ListRecrawlRequestsAction() {
        super(Permission.COMMON);
    }

    @Override
    public ListRecrawlRequestsResponse process(ListRecrawlRequestsRequest request) {
        DateTime dateFrom = request.getDateFrom();
        DateTime dateTo = request.getDateTo();
        int offset = request.getOffset();
        int limit = request.getLimit();

        int count = addUrlRequestsService.count(request.getHostId(), dateFrom, dateTo);
        if (count == 0 || offset >= count) {
            return new ListRecrawlRequestsResponse(Collections.emptyList(), count);
        }

        List<UrlForRecrawl> urlForRecrawls = addUrlRequestsService.list(request.getHostId(), dateFrom,
                dateTo, offset, limit);
        List<RecrawlRequestInfo> requestInfos = urlForRecrawls.stream()
                .map(RecrawlRequestInfo::fromUrlForRecrawl)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        return new ListRecrawlRequestsResponse(requestInfos, count);
    }

    @Required
    public void setAddUrlRequestsService(AddUrlRequestsService addUrlRequestsService) {
        this.addUrlRequestsService = addUrlRequestsService;
    }
}
