package com.agiledeveloper.xmlprocessing;
import javax.xml.parsers.*;
import org.w3c.dom.*;

public class InfoReader
{
	// We assume that the last name is unique (not a realistic
	// assumption, but then this is a ficticious example any ways)

	private String lastNameToLookup;
	private Element personNode;

	public InfoReader(String theLastNameToLookup) throws Exception
	{
		lastNameToLookup = theLastNameToLookup;
		DocumentBuilderFactory factory =
			DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document document = builder.parse("c:/temp/data/info.xml"); 

		NodeList persons = document.getElementsByTagName("person");

		for(int i = 0; i < persons.getLength(); i++)
		{
			Element person = (Element) persons.item(i);
			String lastName = person.getElementsByTagName("last").item(0).getFirstChild().getNodeValue();
			if (lastName.equals(lastNameToLookup))
			{
				personNode = (Element) persons.item(i);
				break;
			}
		}
	}

	public String getFullName()
	{
		if (personNode == null)
			return "Name not found";

		String lastName = personNode.getElementsByTagName("last").item(0).getFirstChild().getNodeValue();
		String firstName = personNode.getElementsByTagName("first").item(0).getFirstChild().getNodeValue();
		return firstName + " " + lastName;
	}

	public String getRecord()
	{
		if (personNode == null)
			return "Name not found";

		String record = personNode.getElementsByTagName("record").item(0).getFirstChild().getNodeValue();
		return record;
	}

	public String getPictureFileName()
	{
		String fileName = null;
		if (personNode != null)
		{
			fileName = personNode.getElementsByTagName("img").item(0).getFirstChild().getNodeValue();
		}
		return fileName;
	}

	public static void main(String[] args)
	{
		// Test code
		try
		{
			InfoReader reader = new InfoReader("Dijkstra");
			System.out.println(reader.getFullName());
			System.out.println(reader.getRecord());
		}
		catch(Exception e)
		{
			System.out.println("Error: " + e);
			e.printStackTrace();
		}

		try
		{
			InfoReader reader = new InfoReader("blah");
			System.out.println(reader.getFullName());
			System.out.println(reader.getRecord());
		}
		catch(Exception e)
		{
			System.out.println("Error: " + e);
			e.printStackTrace();
		}
	}
}