package ru.yandex.wmconsole.servantlet.hostname;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.data.DisplayNameModerationStateEnum;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmconsole.service.error.WMCUserProblem;
import ru.yandex.wmconsole.util.HostElementWrapper;
import ru.yandex.wmtools.common.data.wrappers.SimpleWrapper;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;
import ru.yandex.wmtools.common.util.XmlConvertableCollectionWrapper;

/**
 * Shows information about hostname case.
 *
 * @author ailyin
 */
public class HostnameInfoServantlet extends WMCAuthorizedHostOperationServantlet {
    private static final Logger log = LoggerFactory.getLogger(HostnameInfoServantlet.class);
    private NewWebmasterProxyService newWebmasterProxyService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId)
            throws UserException, InternalException {
        log.debug("HostnameInfo: Started");

        BriefHostInfo briefHostInfo = getHostInfo(req, true, userId, true, true);

        if (isIDN(briefHostInfo.getName())) {
            throw new UserException(WMCUserProblem.IDN_ARE_NOT_SUPPORTED,
                    "Can't change display name of a host with IDN: " + briefHostInfo.getName());
        }

        NewWebmasterProxyService.HostNameInfoResponse response = newWebmasterProxyService.getHostNameInfo(briefHostInfo);

        SimpleWrapper displayNameWrapper = (response == null)
                ? null : new SimpleWrapper<Object>(response.displayName, "display-name");
        SimpleWrapper moderationStateWrapper = (response == null)
                ? null : new SimpleWrapper<Object>(response.state, "moderation-state");
        XmlConvertableCollectionWrapper collectionWrapper = new XmlConvertableCollectionWrapper(Arrays.asList(displayNameWrapper, moderationStateWrapper));

        res.addData(new HostElementWrapper(collectionWrapper, briefHostInfo));
        log.debug("HostnameInfo: Finished");
    }

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