package inc.monsters.mias;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.faces.context.FacesContext;

import org.apache.commons.digester.Digester;
import org.xml.sax.SAXException;

public class FaceletsFunctions {

	private static Quote lastQuote;
	private static Quotes quotesList;
	
	private static void readXMLFile() {
		Digester digester = new Digester();
		digester.setValidating(false);

		digester.addObjectCreate("quotes", Quotes.class);
		digester.addObjectCreate("quotes/quote", Quote.class);
		digester.addBeanPropertySetter("quotes/quote/text", "text");
		digester.addBeanPropertySetter("quotes/quote/author", "author");
		digester.addSetNext( "quotes/quote", "addQuote" );

		FacesContext context = FacesContext.getCurrentInstance();
		URL url;
		try {
			url = context.getExternalContext().getResource("/quotes.xml");
			quotesList = (Quotes) digester.parse(url);
		} catch (MalformedURLException e) {
			System.out.println("Quotes file could not be found. Malformed URL: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("Quotes file could not be opened. IO Exception: " + e.getMessage());
		} catch (SAXException e) {
			System.out.println("Quotes file could not be read. Sax Exception: " + e.getMessage());
		} finally {
			digester = null;
		}
		if (quotesList == null) {
			quotesList = new Quotes();
		}
	}

	private static Quotes getQuotes() {
		if (quotesList == null) {
			readXMLFile();
		}
		return quotesList;
	}

	public static String getQuoteOfTheDay() {
		lastQuote = getQuotes().getRandomQuote();
		return lastQuote.getText();
	}

	public static String getAuthorOfTheDay() {
		if (null == lastQuote) {
			return "";
		} else {
			return lastQuote.getAuthor();
		}
	}
}