import java.io.*;
import org.w3c.dom.*;

/**
 * An encapsulation of a Person.
 * 
 * This is an example of "naive" serialization.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0XML
 */
public class Person
{
    private Address       address;
    private int           age;
    private PhoneNumber[] phoneNumbers;
    private String        firstName, lastName;
    
    /**
     * Construct an empty Person object.
     */
    private Person()
    {
    }

    /**
     * Populate the attributes of this Person object from
     * an XML representation.
     * 
     * @param source  The XML representation
     */
    public void fromXML(Element source)
    {
        NodeList nodes;
        
        firstName  = source.getAttribute("firstName");
        lastName   = source.getAttribute("lastName");
        age        = Integer.parseInt(source.getAttribute("age"));
        
        nodes = source.getElementsByTagName("Address");
        address = Address.parseAddress((Element)nodes.item(0));
        
        nodes = source.getElementsByTagName("PhoneNumber");
        phoneNumbers = new PhoneNumber[nodes.getLength()];
        for (int i=0; i<nodes.getLength(); i++)
        {
            phoneNumbers[i] = PhoneNumber.parsePhoneNumber((Element)nodes.item(i));
        }
    }
    
    /**
     * Construct a Person object from an XML representation.
     * 
     * @param source  The XML representation
     * @return        The Person object
     */
    public static Person parsePerson(Element source)
    {
        Person result = new Person();
        result.fromXML(source);
        return result;
    }

    /**
     * Create an XML representation of this Person.
     * 
     * @return The XML representation
     */
    public String toXML()
    {
        String result = String.format("<Person firstName=\"%s\" lastName=\"%s\" age=\"%s\" >",
                                      firstName, lastName, age);
        
        result += "\n" + address.toXML();
        for (int i=0; i<phoneNumbers.length; i++)
        {
            result += "\n" + phoneNumbers[i].toXML();
        }
        
        result += "\n" + "</Person>";
        
        return result;
    }

}
