import java.text.SimpleDateFormat;

import java.io.*;
import java.net.*;
import java.util.*;

public class FeedCreator
{
	private static final SimpleDateFormat sim = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss");

	PrintWriter strOut;

	FeedCreator(String filePath) throws Exception
	{
		strOut = new PrintWriter(filePath,"UTF-8");
	}

	public void AppendItem(RssItem item) throws Exception
	{
		Date pubDate = new Date(item.date.getTime() - TimeZone.getDefault().getDSTSavings());

		strOut.println("\t<item>");
		strOut.println("\t\t<title><![CDATA[" + item.title + "]]></title>");
		strOut.println("\t\t<link><![CDATA[" + item.link + "]]></link>");
		strOut.println("\t\t<guid><![CDATA[" + item.guid + "]]></guid>");
		strOut.println("\t\t<pubDate>" + sim.format(pubDate) + " " + "GMT" + "</pubDate>");
		strOut.println("\t\t<description><![CDATA[\n\t\t\t" + item.content.replaceAll("\n","\n\t\t\t").trim() + "\n\t\t]]></description>");
		strOut.println("\t</item>");
	}

	public void WriteHeader(String title,String des,String link,String selfLink,Date feedDate) throws Exception
	{
		Date pubDate = new Date(feedDate.getTime() - TimeZone.getDefault().getDSTSavings());

		strOut.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
		strOut.println("<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">");
		strOut.println("<channel>");
		if(!StrNullOrEmpty(selfLink))
			strOut.println("<atom:link href=\"" + selfLink + "\" rel=\"self\" type=\"application/rss+xml\" />");
		strOut.println("\t<title>" + title + "</title>");
		strOut.println("\t<description>" + des + "</description>");
		if(!StrNullOrEmpty(link))
			strOut.println("\t<link>" + link + "</link>");
		strOut.println("\t<pubDate>" + sim.format(pubDate) + " " + "GMT" + "</pubDate>");
	}

	public void WriteFooter() throws Exception
	{
		strOut.println("</channel>");
		strOut.println("</rss>");
	}

	public void println(String line)
	{
		strOut.println(line);
	}

	public void Flush() throws Exception
	{
		strOut.flush();
	}

	public void Close() throws Exception
	{
		this.Flush();
		strOut.close();
	}

	private static boolean StrNullOrEmpty(String str)
	{
		return str==null || str.length()==0;
	}
}