package com.agilex.vamf.utils;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;

import com.agilex.vamf.missionhealth.domain.atom.AtomLink;
import com.agilex.vamf.missionhealth.domain.atom.AtomLinks;
import com.sun.syndication.feed.synd.SyndContentImpl;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndEntryImpl;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndFeedImpl;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.SyndFeedOutput;

public class AtomUtility {
	public static SyndFeed createAtomFeed(AtomLinks links, URI feedUri, String feedTitle) {
		String feedType = "rss_2.0";

		SyndFeed feed = new SyndFeedImpl();
		feed.setFeedType(feedType);

		feed.setTitle(feedTitle);
		feed.setLink(feedUri.toString());
		feed.setDescription(feedTitle);

		List<SyndEntry> entries = new ArrayList<SyndEntry>();

		if (links != null) {
			SyndEntryImpl entry;
			SyndContentImpl description;
			for (AtomLink link : links) {
				entry = new SyndEntryImpl();
				entry.setTitle(link.getTitle());
				entry.setLink(link.getHref().toString());
				description = new SyndContentImpl();
				description.setType(link.getType());
				entry.setDescription(description);
				entries.add(entry);
			}
		}

		feed.setEntries(entries);

		return feed;
	}

	public static Document feedToXml(SyndFeed feed) {
		SyndFeedOutput output = new SyndFeedOutput();
		Document xml;
		try {
			xml = output.outputW3CDom(feed);
		} catch (FeedException e) {
			throw new RuntimeException(e);
		}
		return xml;
	}

	public static SyndFeed xmlToFeed(Document xml) {
		SyndFeedInput input = new SyndFeedInput();
		SyndFeed feed;
		try {
			feed = input.build(xml);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return feed;
	}
}
