package ru.yandex.wmconsole.servantlet.poll;

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.AnswerTypeEnum;
import ru.yandex.wmconsole.data.poll.QuestionInfo;
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;

/**
 * Редактирование вопроса
 *
 * User: azakharov
 * Date: 14.02.13
 * Time: 17:28
 */
public class EditQuestionServantlet extends WMCAuthenticationServantlet {

    private static final String PARAM_POLL_ID = "poll_id";
    private static final String PARAM_QUESTION_ID = "question_id";
    private static final String PARAM_TYPE_ID = "type_id";
    private static final String PARAM_TEXT = "text";
    private static final String PARAM_DESCRIPTION = "description";
    private static final String PARAM_REQUIRED = "required";
    private static final String PARAM_POSITION = "position";
    
    private PollService pollService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        Long pollId = getRequiredLongParam(req, PARAM_POLL_ID);
        Long questionId = getRequiredLongParam(req, PARAM_QUESTION_ID);
        Integer typeId = getRequiredIntParam(req, PARAM_TYPE_ID);
        String text = getRequiredStringParam(req, PARAM_TEXT);
        String description = getStringParam(req, PARAM_DESCRIPTION);
        Boolean required = getRequiredBooleanParam(req, PARAM_REQUIRED);
        Integer position = getIntParam(req, PARAM_POSITION);

        if (text.isEmpty() || text.length() > 200) {
            throw new UserException(WMCUserProblem.POLL_QUESTION_TEXT_SIZE_INVALID, "question text size invalid");
        }

        if (description != null && description.length() > 100) {
            throw new UserException(WMCUserProblem.POLL_QUESTION_DESCRIPTION_SIZE_INVALID, "question text size invalid");
        }

        AnswerTypeEnum answerType = AnswerTypeEnum.R.fromValueOrNull(typeId);
        if (answerType == null) {
            throw new UserException(WMCUserProblem.POLL_QUESTION_TYPE_INVALID, "type is not supported");
        }

        position = position != null ? position : 1;

        QuestionInfo questionInfo = new QuestionInfo(
                questionId, pollId, answerType, text, description, required, position);

        pollService.persistQuestion(questionInfo, userId);
    }

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