package ru.yandex.wmconsole.servantlet.drafts;

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

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

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.framework.pager.Pager;
import ru.yandex.wmconsole.data.info.PersonalDraftMessageInfo;
import ru.yandex.wmconsole.data.wrappers.PersonalDraftMessageWrapper;
import ru.yandex.wmconsole.service.IWMCUserInfoService;
import ru.yandex.wmconsole.service.PersonalDraftMessagesService;
import ru.yandex.wmconsole.service.WMCUserInfoService;
import ru.yandex.wmtools.common.data.info.WMUserInfo;
import ru.yandex.wmtools.common.data.wrappers.UserInfoWrapper;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.servantlet.AuthenticationServantlet;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

public class DraftMessageRecipientsListServantlet extends AuthenticationServantlet {
    private static final String PARAM_MESSAGE_ID = "message";

    private PersonalDraftMessagesService personalDraftMessagesService;
    private IWMCUserInfoService userInfoService;

    @Override
    public void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        checkService(personalDraftMessagesService, PersonalDraftMessagesService.class);
        checkService(userInfoService, WMCUserInfoService.class);

        long messageId = getRequiredLongParam(req, PARAM_MESSAGE_ID);

        Pager pager = getOutputStrategy().createPager();

        List<Long> recipientsList = personalDraftMessagesService.getRecipientsListForMessage(messageId, pager);
        List<WMUserInfo> userInfoList = new ArrayList<WMUserInfo>(recipientsList.size());
        for (Long aRecipientsList : recipientsList) {
            userInfoList.add(userInfoService.getUserInfo(aRecipientsList));
        }

        res.addData(XmlConvertableCollectionWrapper.wrap(userInfoList, UserInfoWrapper.class, "recipients-list"));
        res.addData(pager);

        // get message
        PersonalDraftMessageInfo draftMessage = personalDraftMessagesService.getDraftMessage(messageId);
        res.addData(new PersonalDraftMessageWrapper(draftMessage));
    }

    @Required
    public void setPersonalDraftMessagesService(PersonalDraftMessagesService personalDraftMessagesService) {
        this.personalDraftMessagesService = personalDraftMessagesService;
    }

    @Required
    public void setUserInfoService(IWMCUserInfoService userInfoService) {
        this.userInfoService = userInfoService;
    }
}
