package ru.yandex.wmconsole.servantlet.poll;

import java.util.LinkedList;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.common.util.xml.XmlConvertable;
import ru.yandex.wmconsole.data.poll.PollInfo;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.service.PollService;
import ru.yandex.wmconsole.util.XmlUtil;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.InternalProblem;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

/**
 * User: azakharov
 * Date: 26.03.12
 * Time: 13:33
 */
public class PollListServantlet extends WMCAuthenticationServantlet {
    private static final Logger log = LoggerFactory.getLogger(PollListServantlet.class);

    public static final String TAG_POLL_LIST = "poll-list";

    private PollService pollService;

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

        //  Получаем список опросов
        final Pager pager = createOutputStrategy(req).createPager();
        final List<PollInfo> pollList = pollService.getPollList(pager);

        // Формируем представление списка опросов
        final List<XmlConvertable> pollListView = new LinkedList<XmlConvertable>();
        for (final PollInfo poll : pollList) {
            try {
                final XmlConvertable view = XmlUtil.xmlConvertable(poll);
                pollListView.add(view);
            } catch (JAXBException e) {
                log.error("Jaxb marshalling exception", e);
                throw new InternalException(InternalProblem.INTERNAL_PROBLEM, "Jaxb marshalling exception " + e.getCause());
            }
        }

        // Выдаем результат наружу
        res.addData(new XmlConvertableCollectionWrapper(pollListView, TAG_POLL_LIST));
        res.addData(pager);
    }

    @Required
    public void setPollService(PollService pollService) {
        this.pollService = pollService;
    }
}
