package ru.yandex.wmconsole.servantlet.api;

import org.springframework.beans.factory.annotation.Required;
import ru.yandex.common.framework.core.ServRequest;
import ru.yandex.common.framework.core.ServResponse;
import ru.yandex.webmaster.viewer.service.NewWebmasterProxyService;
import ru.yandex.wmconsole.authorization.ApiOAuthPermission;
import ru.yandex.wmconsole.data.FakeUser;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.error.ClientException;
import ru.yandex.wmconsole.error.ClientProblem;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author ailyin
 */
public class ApiRemoveHostServantlet extends AbstractApiServantlet {
    private static final String PARAM_HOST = "host";
    private NewWebmasterProxyService newWebmasterProxyService;

    @Override
    public void apiDoProcess(ServRequest req, ServResponse res, long userId) throws ClientException, InternalException {
        String stringValue = req.getParam(PARAM_HOST, true);
        if (stringValue == null) {
            throw new ClientException(ClientProblem.REQUIRED_PARAM_MISSED,
                    "Required param missed: " + PARAM_HOST, PARAM_HOST);
        }

        long hostId;
        try {
            hostId = Long.decode(stringValue);
        } catch (NumberFormatException e) {
            throw new ClientException(ClientProblem.ILLEGAL_VALUE_TYPE,
                    "Invalid param: " + PARAM_HOST, e, PARAM_HOST, stringValue);
        }
        BriefHostInfo hostInfo = getHostInfoService().getBriefHostInfoByIdOrName(String.valueOf(hostId));
        if (hostInfo != null) {
            newWebmasterProxyService.deleteHost(userId, hostInfo);
        }
        getHostInfoService().removeHosts(userId, FakeUser.API, hostId);
    }

    @Override
    public ApiOAuthPermission getRequiredPermission() {
        return ApiOAuthPermission.COMMON_OPERATIONS;
    }

    @Required
    public void setNewWebmasterProxyService(NewWebmasterProxyService newWebmasterProxyService) {
        this.newWebmasterProxyService = newWebmasterProxyService;
    }
}
