package ru.yandex.wmconsole.servantlet.moderation.hostnames;

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.DisplayNameModerationStateEnum;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.servantlet.WMCAuthenticationServantlet;
import ru.yandex.wmconsole.service.CheckHostNameService;
import ru.yandex.wmconsole.service.DisplayNameModerationService;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;

public class DisplayNameModeratorIssueServantlet extends WMCAuthenticationServantlet {
    private static final String PARAM_MODERATION_NAME = "new-name";
    private static final String PARAM_MODERATION_STATE = "new-state";

    private DisplayNameModerationService displayNameModerationService;
    private CheckHostNameService checkHostnameService;

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

        BriefHostInfo hostInfo = getHostInfo(req);

        Integer state = getIntParam(req, PARAM_MODERATION_STATE);
        if (state == null) {
            String moderationName = getStringParam(req, PARAM_MODERATION_NAME);
            if (moderationName == null) {
                throw new UserException(UserProblem.REQUIRED_PARAM_MISSED,
                        "Required param missed: " + PARAM_MODERATION_STATE + "|" + PARAM_MODERATION_NAME,
                        PARAM_MODERATION_STATE);
            }

            checkHostnameService.checkDisplayName(hostInfo, moderationName);

            displayNameModerationService.changeDisplayName(hostInfo, moderationName, userId, DisplayNameModerationStateEnum.MODERATOR_ISSUED);
        } else {
            displayNameModerationService.changeModerationState(hostInfo, DisplayNameModerationStateEnum.R.fromValueOrNull(state), userId);
        }
    }

    @Required
    public void setDisplayNameModerationService(DisplayNameModerationService hostNameService) {
        this.displayNameModerationService = hostNameService;
    }

    @Required
    public void setCheckHostNameService(CheckHostNameService checkHostnameService) {
        this.checkHostnameService = checkHostnameService;
    }
}
