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.AnswerOptionInfo;
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: 19.02.13
 * Time: 17:57
 */
public class EditAnswerOptionServantlet extends WMCAuthenticationServantlet {
    
    private static final String PARAM_OPTION_ID = "option_id";
    private static final String PARAM_TEXT = "text";
    private static final String PARAM_DESCRIPTION = "description";
    private static final String PARAM_SCORE = "score";
    private static final String PARAM_NUMBER = "number";
    private static final String PARAM_TEXT_EXPECTED = "text_expected";
    
    private PollService pollService;
    
    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        final long optionId = getRequiredLongParam(req, PARAM_OPTION_ID);
        AnswerOptionInfo oldOption = pollService.getAnswerOptionById(optionId);
        if (oldOption == null) {
            throw new UserException(WMCUserProblem.POLL_OPTION_NOT_FOUND, "option " + optionId + " not found in db");
        }
        final String text = getStringParam(req, PARAM_TEXT, oldOption.getText());
        final String description = getStringParam(req, PARAM_DESCRIPTION, oldOption.getDescription());
        Integer score = getIntParam(req, PARAM_SCORE);
        if (score == null) {
            score = oldOption.getScore();
        }
        Integer number = getIntParam(req, PARAM_NUMBER);
        if (number == null) {
            number = oldOption.getNumber();
        }
        Boolean textExpected = getBooleanParam(req, PARAM_TEXT_EXPECTED, oldOption.isTextExpected());

        AnswerOptionInfo newOption = new AnswerOptionInfo(
                optionId, oldOption.getQuestionId(), text, description, number, score, textExpected);

        pollService.editAnswerOption(oldOption, newOption);
    }

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