package ru.yandex.wmconsole.servantlet.poll;

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.data.poll.PollStatusEnum;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.service.PollService;
import ru.yandex.wmconsole.service.error.WMCUserProblem;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;

/**
 * User: azakharov
 * Date: 27.03.12
 * Time: 12:31
 */
public class EditPollServantlet extends WMCAuthenticationServantlet {
    private static final Logger log = LoggerFactory.getLogger(EditPollServantlet.class);

    private static final String PARAMN_POLL_ID = "poll_id";
    private static final String PARAM_POLL_TITLE = "title";
    private static final String PARAM_POLL_DESCRIPTION = "description";
    private static final String PARAM_POLL_STATE = "state";

    private PollService pollService;

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

        // Идентификатор опроса
        final long pollId = getRequiredLongParam(req, PARAMN_POLL_ID);
        // Заголовок опроса
        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, PARAM_POLL_DESCRIPTION);
        // Статус опроса
        final PollStatusEnum status = PollStatusEnum.valueOf(getRequiredStringParam(req, PARAM_POLL_STATE));
        if (status == null) {
            throw new UserException(UserProblem.REQUIRED_PARAM_MISSED,
                    "Required param missed: " + PARAM_POLL_STATE, PARAM_POLL_STATE);
        }
        // Собираем опрос
        final PollInfo poll = new PollInfo(pollId, pollTitle, pollDescription, status);

        // Сохраняем опрос в базе
        pollService.persistPoll(poll, userId);
    }

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