package ru.yandex.webmaster3.viewer.http.url.checker3;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.url.checker3.dao.UrlCheckRequests2YDao;
import ru.yandex.webmaster3.storage.url.common.data.UrlCheckRequestData;
import ru.yandex.webmaster3.viewer.http.AbstractUserVerifiedHostAction;
import ru.yandex.webmaster3.viewer.http.url.checker3.data.UrlCheckRequest;

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

/**
 * @author leonidrom
 */
@ReadAction
@Component("/urlchecker3/requestsList")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class GetUrlCheckRequestListAction extends AbstractUserVerifiedHostAction<GetUrlCheckRequestListRequest, GetUrlCheckRequestListResponse> {
    private final UrlCheckRequests2YDao urlCheckRequests2YDao;

    @Override
    public GetUrlCheckRequestListResponse process(GetUrlCheckRequestListRequest request) {
        var requests = urlCheckRequests2YDao.getRequests(request.getHostId());
        requests.sort(Comparator.comparing(UrlCheckRequests2YDao.Record::createdTime).reversed());

        // pagination
        PageUtils.Pager pager = PageUtils.getPage(request.getP(), request.getPSize());
        List<UrlCheckRequest> resultPage = requests.stream()
                .skip(pager.toRangeStart())
                .limit(pager.getPageSize())
                .map(r -> new UrlCheckRequest(r.requestId(), r.url(), r.deviceType(), r.createdTime()))
                .collect(Collectors.toList());

        return new GetUrlCheckRequestListResponse.NormalResponse(requests.size(), resultPage);
    }
}
