package ru.yandex.wmconsole.servantlet.contentpreview;

import org.springframework.beans.factory.annotation.Required;

import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.common.util.collections.Cf;
import ru.yandex.webmaster.common.contentpreview.ContentPreviewSettings;
import ru.yandex.webmaster.common.contentpreview.ContentPreviewSettingsService;
import ru.yandex.webmaster.common.contentpreview.ContentPreviewState;
import ru.yandex.webmaster.common.contentpreview.ContentPreviewType;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.data.wrappers.NoDataWrapper;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;

/**
 * @author aherman
 */
public class SetContentPreviewSettingsServantlet extends WMCAuthorizedHostOperationServantlet {
    private static final String PARAM_DESKTOP_STATE = "desktop-state";
    private static final String PARAM_MOBILE_STATE = "mobile-state";

    private ContentPreviewSettingsService contentPreviewSettingsService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        String desktopStr = getRequiredStringParam(req, PARAM_DESKTOP_STATE);
        ContentPreviewState desktopState = ContentPreviewState.R.valueOfOrUnknown(desktopStr);
        String mobileStr = getRequiredStringParam(req, PARAM_MOBILE_STATE);
        ContentPreviewState mobileState = ContentPreviewState.R.valueOfOrUnknown(mobileStr);
        if (desktopState == ContentPreviewState.UNKNOWN) {
            throw new UserException(UserProblem.ILLEGAL_PARAM_VALUE, "Illegal desktop preview state",
                    PARAM_DESKTOP_STATE, desktopStr);
        }
        if (mobileState == ContentPreviewState.UNKNOWN) {
            throw new UserException(UserProblem.ILLEGAL_PARAM_VALUE, "Illegal mobile preview state",
                    PARAM_MOBILE_STATE, mobileStr);
        }

        BriefHostInfo hostInfo = getHostInfoAndVerify(req, userId);
        ContentPreviewSettings mobileSettings = new ContentPreviewSettings(hostInfo, ContentPreviewType.MOBILE, mobileState);
        ContentPreviewSettings desktopSettings = new ContentPreviewSettings(hostInfo, ContentPreviewType.DESKTOP, desktopState);
        contentPreviewSettingsService.changeSetting(Cf.list(mobileSettings, desktopSettings));
        res.addData(new NoDataWrapper("ok"));
    }

    @Required
    public void setContentPreviewSettingsService(ContentPreviewSettingsService contentPreviewSettingsService) {
        this.contentPreviewSettingsService = contentPreviewSettingsService;
    }
}
