package ru.yandex.wmconsole.servantlet.contentpreview;

import java.util.List;

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.xml.XmlConvertable;
import ru.yandex.webmaster.common.contentpreview.ContentPreviewSettings;
import ru.yandex.webmaster.common.contentpreview.ContentPreviewSettingsService;
import ru.yandex.webmaster.common.util.xml.SimpleXmlBuilder;
import ru.yandex.wmconsole.data.info.BriefHostInfo;
import ru.yandex.wmconsole.servantlet.WMCAuthorizedHostOperationServantlet;
import ru.yandex.wmtools.common.error.InternalException;
import ru.yandex.wmtools.common.error.UserException;

/**
 * @author aherman
 */
public class GetContentPreviewSettingsServantlet extends WMCAuthorizedHostOperationServantlet {
    private ContentPreviewSettingsService contentPreviewSettingsService;

    @Override
    protected void doProcess(ServRequest req, ServResponse res, long userId) throws UserException, InternalException {
        BriefHostInfo hostInfo = getHostInfoAndVerify(req, userId);
        List<ContentPreviewSettings> settings = contentPreviewSettingsService.getSettings(hostInfo);
        res.addData(new ContentPreviewResponse(hostInfo, settings));
    }

    private static class ContentPreviewResponse implements XmlConvertable {
        private final BriefHostInfo hostInfo;
        private final List<ContentPreviewSettings> settings;

        private ContentPreviewResponse(BriefHostInfo hostInfo,
                List<ContentPreviewSettings> settings)
        {
            this.hostInfo = hostInfo;
            this.settings = settings;
        }

        @Override
        public void toXml(StringBuilder stringBuilder) {
            SimpleXmlBuilder xml = new SimpleXmlBuilder(stringBuilder);
            xml.open("content-preview").attribute("host-id", hostInfo.getId());
            for (ContentPreviewSettings setting : settings) {
                xml.open("preview")
                        .attribute("type", setting.getType())
                        .attribute("state", setting.getState());
                xml.close();
            }
            xml.close(); // content-preview
        }
    }

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