import java.io.*;
import javax.json.*;
import javax.json.stream.*;

/**
 * An encapsulation of a Person.
 * 
 * This is an example of "naive" serialization.
 * 
 * @author  Prof. David Bernstein, James Madison University
 * @version 1.0JSON
 */
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
     * a JSON representation.
     * 
     * @param source  The JSON representation
     */
    public void fromJSON(JsonObject source)
    {
        firstName = source.getString("firstName");
        lastName  = source.getString("lastName");
        age       = source.getInt("age");
        
        address = Address.parseAddress(source.getJsonObject("address"));
        
        JsonArray pns = source.getJsonArray("phoneNumbers");
        phoneNumbers = new PhoneNumber[pns.size()];
        for (int i=0; i<phoneNumbers.length; i++)
        {
            JsonObject pn = pns.getJsonObject(i);
            phoneNumbers[i] = PhoneNumber.parsePhoneNumber(pn);
        }
    }
    
    /**
     * Construct a Person object from a JSON representation.
     * 
     * @param source  The JSON representation
     * @return        The Person object
     */
    public static Person parsePerson(JsonObject source)
    {
        Person result = new Person();
        result.fromJSON(source);
        return result;
    }

    /**
     * Create a JSON representation of this Person.
     * 
     * @return  A String containing the JSON representation
     */
    public String toJSON()
    {
        StringWriter out = new StringWriter();
        JsonGenerator g = Json.createGenerator(out); 
        toJSON(g, null);
        g.close();
        
        return out.toString();
    }
    
    /**
     * Create a JSON representation of this Person using the
     * given JsonGenerator.
     * 
     * @param g     The JsonGenerator to use
     * @param name  The name for the JsonObject (or null for none)
     */
    public void toJSON(JsonGenerator g, String name)
    {
        if (name == null) g.writeStartObject();
        else              g.writeStartObject(name);
          g.write("firstName", firstName);
          g.write("lastName", lastName);
          g.write("age", 25);
          address.toJSON(g, "address");
          g.writeStartArray("phoneNumbers");
            for (int i=0; i<phoneNumbers.length; i++)
            {
                phoneNumbers[i].toJSON(g, null);
            }
          g.writeEnd();
        g.writeEnd();
    }
}
