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.webmaster.common.host.dao.TblHostsMainDao;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.info.HostOwnersDraftMessageInfo;
import ru.yandex.wmconsole.data.wrappers.BriefHostInfoWrapper;
import ru.yandex.wmconsole.data.wrappers.HostOwnersDraftMessageWrapper;
import ru.yandex.wmconsole.service.HostOwnersDraftMessagesService;
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;

/**
 * @author avhaliullin
 */
public class DraftMessageHostsListServantlet extends AuthenticationServantlet {
    private static final String PARAM_MESSAGE_ID = "message";

    private HostOwnersDraftMessagesService hostOwnersDraftMessagesService;
    private TblHostsMainDao tblHostsMainDao;

    @Override
    public void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {

        long messageId = getRequiredLongParam(req, PARAM_MESSAGE_ID);

        Pager pager = createOutputStrategy(req).createPager();

        List<Long> hosts = hostOwnersDraftMessagesService.getHostsListForMessage(messageId, pager);
        List<BriefHostInfo> userInfoList = new ArrayList<BriefHostInfo>(hosts.size());
        for (Long host : hosts) {
            BriefHostInfo hostInfo = tblHostsMainDao.getBriefHostInfoByHostId(host);
            userInfoList.add(hostInfo);
        }

        res.addData(XmlConvertableCollectionWrapper.wrap(userInfoList, BriefHostInfoWrapper.class, "hosts-list"));
        res.addData(pager);

        // get message
        HostOwnersDraftMessageInfo draftMessage = hostOwnersDraftMessagesService.getDraftMessage(messageId);
        res.addData(new HostOwnersDraftMessageWrapper(draftMessage));
    }

    @Required
    public void setHostOwnersDraftMessagesService(HostOwnersDraftMessagesService personalDraftMessagesService) {
        this.hostOwnersDraftMessagesService = personalDraftMessagesService;
    }

    @Required
    public void setTblHostsMainDao(TblHostsMainDao tblHostsMainDao) {
        this.tblHostsMainDao = tblHostsMainDao;
    }
}
