package ru.yandex.webmaster3.admin.action.mirrors;

import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Required;

import ru.yandex.autodoc.common.doc.annotation.Description;
import ru.yandex.webmaster3.admin.security.action.AdminAction;
import ru.yandex.webmaster3.core.WebmasterException;
import ru.yandex.webmaster3.core.data.WebmasterHostId;
import ru.yandex.webmaster3.core.metrics.Category;
import ru.yandex.webmaster3.core.http.ReadAction;
import ru.yandex.webmaster3.core.util.IdUtils;
import ru.yandex.webmaster3.core.util.PageUtils;
import ru.yandex.webmaster3.storage.admin.security.AccessObjectEnum;
import ru.yandex.webmaster3.storage.mirrors.data.MirrorRequest;
import ru.yandex.webmaster3.storage.mirrors.service.MainMirrorService;

/**
 * @author tsyplyaev
 */
@ReadAction
@Description("Список запросов на изменение зеркал")
@Category("mirrors")
public class ListMirrorRequestsAction extends AdminAction<ListMirrorRequestsRequest, ListMirrorRequestsResponse> {
    private MainMirrorService mainMirrorService;

    public ListMirrorRequestsAction() {
        super(AccessObjectEnum.MIRRORS);
    }

    @Override
    public ListMirrorRequestsResponse process(ListMirrorRequestsRequest request) throws WebmasterException {
        WebmasterHostId hostId = IdUtils.urlToHostId(request.getHostName());

        int mirrorRequestCount =
                (int) mainMirrorService.getMirrorRequestCount(hostId, request.getFromDate(), request.getToDate());

        PageUtils.Pager page = PageUtils.getPage(request.getPage(), request.getPageSize(), mirrorRequestCount);
        List<MirrorRequest> requests;
        if (page.isEmpty()) {
            requests = Collections.emptyList();
        } else {
            requests = mainMirrorService.getMirrorRequests(hostId, request.getFromDate(), request.getToDate(), page.toRangeStart() + page.getPageSize());
            int fromIndex = Math.min(page.toRangeStart(), requests.size());
            int toIndex = Math.min(page.toRangeStart() + page.getPageSize(), requests.size());
            requests = requests.subList(fromIndex, toIndex);
        }

        return new ListMirrorRequestsResponse.NormalReponse(requests,
                mirrorRequestCount);
    }

    @Required
    public void setMainMirrorService(MainMirrorService mainMirrorService) {
        this.mainMirrorService = mainMirrorService;
    }
}
