package ru.yandex.wmconsole.notifier.provider;

import java.io.IOException;
import java.io.StringReader;
import java.net.IDN;

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.springframework.beans.factory.annotation.Required;

import ru.yandex.wmconsole.service.HostInfoService;
import ru.yandex.wmtools.common.error.InternalException;

/**
 * @author avhaliullin
 */
public abstract class AbstractHostInfoProvider implements Provider {
    private static final String TAG_HOST = "host";
    private static final String ATTRIBUTE_ID = "id";
    private static final String ATTRIBUTE_HOST_NAME = "name";

    protected HostInfoService hostInfoService;

    protected Element xmlToElement(String xml, String rootName) throws JDOMException {
        Element element;
        try {
            element = new SAXBuilder().build(new StringReader(xml)).getRootElement();
        } catch (IOException e) {
            return null;
            //unreal exception
        }
        Element result = new Element(rootName);
        result.addContent(element.cloneContent());
        return result;
    }

    protected Element getHostElement(long hostId) throws InternalException {
        Element element = new Element(TAG_HOST);
        element.setAttribute(ATTRIBUTE_ID, String.valueOf(hostId));
        final String hostName = hostInfoService.getHostNameByHostId(hostId);
        final String punicodeName = IDN.toUnicode(hostName);
        element.setAttribute(ATTRIBUTE_HOST_NAME, punicodeName);
        return element;
    }

    @Required
    public void setHostInfoService(HostInfoService hostInfoService) {
        this.hostInfoService = hostInfoService;
    }
}
