package com.dubiousoft.sakana;

import java.io.IOException;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.content.res.AssetManager;

public class SceneManager {

	public class Scores {
		int High;
		int Avg;
		int Min;
	}
	
	public class SceneNode {
		public String name;
		public String path;
		public String image;
		public String description;
		public Scores scores = new Scores();
	}
	private Vector<SceneNode> m_scenes = new Vector<SceneNode>();
	
	SceneManager( AssetManager assetManager ) {
		try {
			Utils.LOG( "Loading Scene Manager" );
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
			DocumentBuilder db;
			db = dbf.newDocumentBuilder();
			Document doc = db.parse(assetManager.open( "Scenes/index.xml" ));
			doc.normalize();
			Utils.cleanNode( doc );
			
			Element sceneList = (Element) doc.getFirstChild();
			NodeList scenes = sceneList.getChildNodes();
			for (int i=0; i<scenes.getLength(); ++i) {
				SceneNode newNode = new SceneNode();
				Node xmlNode = scenes.item(i);
				newNode.name = Utils.getChildNode( xmlNode, "Name" ).getTextContent();
				newNode.description = Utils.getChildNode( xmlNode, "Description" ).getTextContent();
				newNode.path = "Scenes/" + Utils.getChildNode( xmlNode, "FileName" ).getTextContent();
				newNode.image = "Scenes/" + Utils.getChildNode( xmlNode, "Image" ).getTextContent();
				Node scoreNode = Utils.getChildNode( xmlNode, "Scores" );
				newNode.scores.High = Integer.parseInt(Utils.getChildNode( scoreNode, "High" ).getTextContent());
				newNode.scores.Avg = Integer.parseInt(Utils.getChildNode( scoreNode, "Avg" ).getTextContent());
				newNode.scores.Min = Integer.parseInt(Utils.getChildNode( scoreNode, "Min" ).getTextContent());
				Utils.LOG( "Adding Scene " + newNode.name);
				m_scenes.add( newNode );
			}

		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public SceneNode getNode( int index ) {
		return m_scenes.get( index );
	}
	
	public int getSize() {
		return m_scenes.size();
	}
}
