package ru.yandex.wmconsole.servantlet.messages.options;

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.LanguageEnum;
import ru.yandex.wmconsole.data.info.UserOptionsInfo;
import ru.yandex.wmconsole.service.UserOptionsService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;
import ru.yandex.wmtools.common.servantlet.AuthenticationServantlet;
import ru.yandex.wmtools.common.service.ValidatorService;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class ChannelOptionsChangeServantlet extends AuthenticationServantlet {
    private static final String EMPTY = "";
    private static final String PARAM_EMAIL = "email";
    private static final String PARAM_LANG = "email-lang";

    private ValidatorService validatorService;
    private UserOptionsService userOptionsService;

    @Override
    public void doProcess(ServRequest req, ServResponse res, long userId) throws InternalException, UserException {
        checkService(userOptionsService, UserOptionsService.class);

        String email = req.getParam(PARAM_EMAIL, true);
        String lang = req.getParam(PARAM_LANG, true);
        // language = null не сохраняется
        LanguageEnum language = LanguageEnum.fromString(lang);
        boolean needSaveEmail = email != null && !email.isEmpty();
        saveEmail(
                userId,
                needSaveEmail ? email : EMPTY,
                language,
                needSaveEmail);
    }

    private void saveEmail(long userId, String email, LanguageEnum emailLang, boolean needVerify) throws InternalException, UserException {
        if (needVerify) {
            if (!validatorService.isEmailValid(userId, email)) {
                throw new UserException(UserProblem.EMAIL_NOT_VERIFIED, "Email is not verified");
            }
        }

        UserOptionsInfo userOptions = userOptionsService.getUserOptions(userId);
        UserOptionsInfo newOptions = userOptions.replaceEmailOptions(email, emailLang);
        userOptionsService.updateUserOptions(newOptions);
    }

    @Required
    public void setValidatorService(ValidatorService validatorService) {
        this.validatorService = validatorService;
    }

    @Required
    public void setUserOptionsService(UserOptionsService userOptionsService) {
        this.userOptionsService = userOptionsService;
    }
}
