//Mr. Bui's solution to AddressBook with ArrayList

import java.io.*;
import java.util.*;

public class AddressBookArrayList
{
	private ArrayList myContacts = new ArrayList();
	
	public AddressBookArrayList()
	{
	}
	
	public AddressBookArrayList(ArrayList newContacts)
	{
		myContacts = newContacts;
	}
	
	public ArrayList getMyContacts()
	{
		return myContacts;
	}
	
	public boolean addContact(Contact newContact)
	{
		return myContacts.add(newContact);
	}
	
	public int size()
	{
		return myContacts.size();
	}
	
	public void print()
	{
		for (int i = 0; i < myContacts.size(); i++)
			System.out.println(myContacts.get(i));
	}
	
	public void printToFile(String filename) throws IOException
	{
		FileWriter fw = new FileWriter( filename, false );
		PrintWriter pw = new PrintWriter( fw, true );
		
		for (int i = 0; i < myContacts.size(); i++)
		{
			Contact tmp = (Contact) myContacts.get(i);
			
			pw.println(tmp.getFirstname());
			pw.println(tmp.getLastname());
			pw.println(tmp.getPhone());
		}
		
		pw.close();
	}
	
	public boolean readFromFile(String filename) throws IOException
	{
		File file = new File( filename );
		
		if(file.exists())
		{
			BufferedReader inFile = new BufferedReader( new FileReader( file ) );
			
			String line = "";
			int i = 0;
			
			for (i = 0; line != null; i++)
			{
				line = inFile.readLine();
			}
			
			inFile.close();
			
			int numContacts = i / 3;
			
			inFile = new BufferedReader( new FileReader( file ) );
			
			for (int j = 0; j < numContacts; j++)
			{
				Contact newContact = new Contact(inFile.readLine(), inFile.readLine(), inFile.readLine());
				addContact(newContact);
			}
	
			return true;
		}

		return false;
	}
	
	public String getPhoneNumber(String fn, String ln)
	{
		for (int i = 0; i < myContacts.size(); i++)
		{
			Contact tmp = (Contact) myContacts.get(i);
			if (fn.equals(tmp.getFirstname()) && ln.equals(tmp.getLastname()))
				return tmp.getPhone();
		}
		
		return null;
	}
	
	public boolean deleteContact(String fn, String ln)
	{
		//use this loop to iterate through the entire array of Contacts
		for (int i = 0; i < myContacts.size(); i++)
		{
			Contact tmp = (Contact) myContacts.get(i);
			//check if the current Contact is the one we're looking for
			if (fn.equals(tmp.getFirstname()) && ln.equals(tmp.getLastname()))
			{
				myContacts.remove(i);
				return true;
			}
		}
		
		//if we get here, then we know that the Contact was never in the array, so we return false
		return false;
	}
}