package ru.yandex.wmconsole.servantlet.mainmirror;

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.info.BriefHostInfo;
import ru.yandex.wmconsole.data.mirror.MirrorGroupActionEnum;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmconsole.service.MirrorGroupsChangeService;
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.util.URLUtil;

import java.net.URL;

/**
 * User: azakharov
 * Date: 19.03.14
 * Time: 14:50
 */
public class MainMirrorChangeServantlet extends WMCAuthorizedHostOperationServantlet {

    private static final String PARAM_ACTION = "action";
    private static final String PARAM_MAIN = "main";

    private MirrorGroupsChangeService mirrorGroupsChangeService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        final String actionName = getRequiredStringParam(req, PARAM_ACTION);
        final MirrorGroupActionEnum action = MirrorGroupActionEnum.fromValueOrNull(actionName);
        if (action == null) {
            throw new UserException(UserProblem.ILLEGAL_PARAM_VALUE, "Unsupported value of parameter action", PARAM_ACTION, actionName);
        }

        final String mainMirrorParam = getStringParam(req, PARAM_MAIN);
        if (mainMirrorParam == null && MirrorGroupActionEnum.RERANGE.equals(action)) {
            throw new UserException(
                    UserProblem.REQUIRED_PARAM_MISSED,
                    "Required parameter " + PARAM_MAIN + " missed",
                    PARAM_MAIN, "");
        }

        BriefHostInfo hostInfo = getHostInfoAndVerify(req, userId);

        final String desiredHostName;
        if (mainMirrorParam == null) {
            desiredHostName = hostInfo.getName();
        } else {
            final URL mainMirrorUrl = prepareUrl(mainMirrorParam, true);
            desiredHostName = URLUtil.getHostName(mainMirrorUrl, false);
        }

        // validate request
        BriefHostInfo oldMainMirrorInfo = mirrorGroupsChangeService.validateMirrorRequest(hostInfo, action, desiredHostName, userId);
        // save request to database
        mirrorGroupsChangeService.saveMirrorRequest(hostInfo, action, desiredHostName, userId, oldMainMirrorInfo.getName());
    }

    @Required
    public void setMirrorGroupsChangeService(MirrorGroupsChangeService mirrorGroupsChangeService) {
        this.mirrorGroupsChangeService = mirrorGroupsChangeService;
    }
}
