package ru.yandex.wmconsole.servantlet.internal.api.verification;

import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Required;
import ru.yandex.webmaster.common.http.Action;
import ru.yandex.webmaster.common.http.ActionRequest;
import ru.yandex.webmaster.common.http.ActionResponse;
import ru.yandex.webmaster.common.http.RequestQueryProperty;
import ru.yandex.webmaster.common.newwmc.DelegationView;
import ru.yandex.wmconsole.data.info.DelegationInfo;
import ru.yandex.wmconsole.service.DelegationsService;

import java.util.ArrayList;
import java.util.List;

/**
 * @author avhaliullin
 */
public class ExportDelegationsAction extends Action<ExportDelegationsAction.Request, ExportDelegationsAction.Response> {
    private DelegationsService delegationsService;

    @Override
    public Response process(Request request) throws Exception {
        List<Pair<DelegationInfo, String>> delegationInfos = delegationsService.listAllDelegations(request.fromId, request.pageSize);
        List<DelegationView> views = new ArrayList<>();
        for (Pair<DelegationInfo, String> pair : delegationInfos) {
            DelegationInfo delegationInfo = pair.getLeft();
            if (delegationInfo == null) {
                continue;
            }
            String hostName = pair.getRight();
            views.add(
                    new DelegationView(
                            delegationInfo.getId(),
                            delegationInfo.getUserIdGave(),
                            delegationInfo.getUserGotInfo().getUserId(),
                            hostName,
                            delegationInfo.getDelegationDate().getTime()
                    )
            );
        }
        return new Response(views);
    }

    public static class Request implements ActionRequest {
        private long fromId;
        private int pageSize;

        @RequestQueryProperty(required = true)
        public void setFromId(long fromId) {
            this.fromId = fromId;
        }

        @RequestQueryProperty(required = true)
        public void setPageSize(int pageSize) {
            this.pageSize = pageSize;
        }
    }

    public static class Response implements ActionResponse {
        private final List<DelegationView> delegations;

        public Response(List<DelegationView> delegations) {
            this.delegations = delegations;
        }

        public List<DelegationView> getDelegations() {
            return delegations;
        }
    }

    @Required
    public void setDelegationsService(DelegationsService delegationsService) {
        this.delegationsService = delegationsService;
    }
}
