package ru.yandex.wmconsole.data.wrappers;

import java.io.UnsupportedEncodingException;
import java.net.IDN;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;

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

import ru.yandex.wmconsole.data.info.SerpLinkInfo;
import ru.yandex.wmtools.common.SupportedProtocols;
import ru.yandex.wmtools.common.util.XmlDataWrapper;

/**
 * @author Andrey Mima (amima@yandex-team.ru)
 */
public class SerpLinkInfoWrapper extends XmlDataWrapper<SerpLinkInfo.SerpLinksPage> {
    private static final Logger log = LoggerFactory.getLogger(SerpLinkInfoWrapper.class);

    private static final String TAG_PAGE = "serplink";
    private static final String ATTRIBUTE_BLOCKED = "block";
    private static final String ATTRIBUTE_URL = "url";
    private static final String ATTRIBUTE_WEIGHT = "weight";
    private static final String ATTRIBUTE_HIDDEN = "hidden";
    private static final String TAG_PAGE_NAME = "name";
    private static final String TAG_PAGE_WEIGHT = "weight";

    public SerpLinkInfoWrapper(SerpLinkInfo.SerpLinksPage data) throws UnsupportedEncodingException {
        super(data, TAG_PAGE);
        addAttribute(ATTRIBUTE_URL, data.getId(), true);
        addAttribute(ATTRIBUTE_BLOCKED, Boolean.toString(data.isBlocked()));
        addAttribute(ATTRIBUTE_WEIGHT, data.getWeight().toString());
        addAttribute(ATTRIBUTE_HIDDEN, data.getHideState().getValue());
        try {
            // TODO: Kids don't do this in constructor!
            URL url = SupportedProtocols.getURL(data.getId());
            addAttribute("url-punycode-host", IDN.toASCII(url.getHost()));
            addAttribute("url-path", url.getFile(), true);
        } catch (MalformedURLException e) {
            log.error("Unable to parse url: " + data.getId(), e);
        } catch (SupportedProtocols.UnsupportedProtocolException e) {
            log.error("Unable to parse url: " + data.getId(), e);
        } catch (URISyntaxException e) {
            log.error("Unable to parse url: " + data.getId(), e);
        }
    }

    @Override
    protected void doToXml(StringBuilder result) {
        for (SerpLinkInfo.SerpLinksPageName pageName : data.getPageNames()) {
            putTag(result, TAG_PAGE_NAME, pageName.getName(), TAG_PAGE_WEIGHT, pageName.getWeight().toString());
        }
    }
}
