package ru.yandex.wmconsole.servantlet;

import java.net.URL;

import javax.xml.bind.JAXBException;

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.service.ZoraService;
import ru.yandex.wmconsole.util.XmlUtil;
import ru.yandex.wmtools.common.SupportedProtocols;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.InternalProblem;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.error.UserProblem;
import ru.yandex.wmtools.common.service.SupportService;

/**
 * Инструмент обновления кэша robots.txt в <a href="http://wiki.yandex-team.ru/Robot/Manual/Zora">zora</>.
 *
 * User: azakharov
 * Date: 23.05.12
 * Time: 12:45
 */
public class RenewHostServantlet extends WMCAuthenticationServantlet {
    private static final String PARAM_HOST = "host";

    private ZoraService zoraService;
    private SupportService supportService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        // Пользователь существует
        assertUserExists(userId);
        // Пользователь саппорт
        if (!supportService.isSupportUser(userId)) {
            throw new UserException(
                    UserProblem.USER_NOT_PERMITTED,
                    "user " + userId + " is not support user");
        }

        String hostName = getRequiredStringParam(req, PARAM_HOST);
        if (!(hostName.matches("^\\d+$"))) {
            final URL host = prepareUrl(hostName, true);
            hostName = SupportedProtocols.getCanonicalHostname(host);
        }
        ZoraService.ZoraResponse response = zoraService.renewHost(hostName);
        try {
            res.addData(XmlUtil.xmlConvertable(response));
        } catch (JAXBException e) {
            throw new InternalException(InternalProblem.JAXB_MARSHALLING_ERROR, "jaxb exception");
        }
    }

    @Required
    public void setSupportService(SupportService supportService) {
        this.supportService = supportService;
    }

    @Required
    public void setZoraService(ZoraService zoraService) {
        this.zoraService = zoraService;
    }
}
