package ru.yandex.wmconsole.servantlet.poll;

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.wmconsole.data.poll.PollInfo;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.service.PollService;
import ru.yandex.wmconsole.service.error.WMCUserProblem;
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;

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

    private static final String PARAM_POLL_TITLE = "title";
    private static final String PARAMN_POLL_DESCRIPTION = "description";

    private PollService pollService;

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

        final String pollTitle = getRequiredStringParam(req, PARAM_POLL_TITLE);
        if (pollTitle == null || pollTitle.trim().length() == 0) {
            throw new UserException(WMCUserProblem.POLL_TITLE_REQUIRED,
                    "Required param missed: " + PARAM_POLL_TITLE, PARAM_POLL_TITLE);
        }
        final String pollDescription = getStringParam(req, PARAMN_POLL_DESCRIPTION);
        final PollInfo pollInfo = pollService.addPoll(pollTitle, pollDescription, userId);
        try {
            res.addData(XmlUtil.xmlConvertable(pollInfo));
        } catch (JAXBException e) {
            log.error("Jaxb marshalling error", e);
            throw new InternalException(InternalProblem.INTERNAL_PROBLEM, "Jaxb marshalling error", e);
        }
    }

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