package nl.powercraft.tagtracker;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

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.os.Environment;
import android.util.Log;

public class XMLParser {

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ArrayList init()
	{
		ArrayList cardID = new ArrayList();
		File root = new File(Environment.getExternalStorageDirectory(), "TagTracker");
	    File xmlfile = new File(root, "tags.log");
		DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = null;
		try {
		    builder = builderFactory.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
		    e.printStackTrace();  
		}
		try {
		    Document document = builder.parse(new FileInputStream(xmlfile));
		    Element rootElement = document.getDocumentElement();
		    NodeList nodes = rootElement.getChildNodes();
		    
		    for(int i=0; i<nodes.getLength(); i++){
		      Node node = nodes.item(i);
		      //Log.d("TagTracker", "[" + i + "] " + node.getNodeName());
		      if(node instanceof Element){
		        //a child element to process
		        Element child = (Element) node;
		        Log.d("TagTracker", "" + (child.getNodeName() == "tag"));
		        if(child.getNodeName().equals("tag"))
		        {
		        	 Log.d("TagTracker", "Toasting...");
		        	 String attribute = child.getAttribute("uid");
		        	 cardID.add(attribute);
		        }
		      }
		    }
		} catch (SAXException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}
		return cardID;	
	}
	
}
