package ru.yandex.wmconsole.viewer.api;

import java.net.URI;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;

import ru.yandex.webmaster.common.util.xml.SimpleXmlBuilder;

/**
 * @author aherman
 */
public class ApiXmlUtils {
    private static final DateTimeFormatter DATE_FORMATTER = ISODateTimeFormat.date();
    private static final DateTimeFormatter DATE_TIME_FORMATTER = ISODateTimeFormat.dateTimeNoMillis();

    public static void link(SimpleXmlBuilder xml, ApiLink apiLink) {
        link(xml, apiLink.getUri(), apiLink.getApiLinkType());
    }

    public static void link(SimpleXmlBuilder xml, URI uri, ApiLinkType apiLinkType) {
        link(xml, uri.toString(), apiLinkType);
    }

    public static void link(SimpleXmlBuilder xml, String uri, ApiLinkType apiLinkType) {
        xml.open("link");
        xml.attribute("href", uri.toString());
        if (apiLinkType != null && apiLinkType != ApiLinkType.UNKNOWN) {
            xml.attribute("rel", apiLinkType.getRel());
        }
        xml.close(); // link
    }

    public static void dateElement(SimpleXmlBuilder xml, String name, Date date) {
        if (date == null) {
            return;
        }
        DateTime dateTime = new DateTime(date);
        xml.element(name, DATE_FORMATTER.print(dateTime));
    }

    public static void dateTimeElement(SimpleXmlBuilder xml, String name, Date date) {
        if (date == null) {
            return;
        }
        DateTime dateTime = new DateTime(date);
        xml.element(name, DATE_TIME_FORMATTER.print(dateTime));
    }
}
