//Mr. Bui's solution to AddressBook

import java.io.*;

public class AddressBook
{
	public static final int MAX_SIZE = 99;
	private int size = 0;
	private Contact [] myContacts = new Contact[MAX_SIZE];
	
	public AddressBook()
	{
	}
	
	public AddressBook(int newSize, Contact [] newContacts)
	{
		size = newSize;
		myContacts = newContacts;
	}
	
	public Contact [] getMyContacts()
	{
		return myContacts;
	}
	
	public boolean addContact(Contact newContact)
	{
		if (size < MAX_SIZE)
		{
			myContacts[size] = newContact;
			size++;
			return true;
		}
		return false;
	}
	
	public int size()
	{
		return size;
	}
	
	public void print()
	{
		for (int i = 0; i < size; i++)
			System.out.println(myContacts[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 < size; i++)
		{
			pw.println(myContacts[i].getFirstname());
			pw.println(myContacts[i].getLastname());
			pw.println(myContacts[i].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 ) );
			
			if (numContacts + size > MAX_SIZE)
				return false;
			
			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 < size; i++)
		{
			if (fn.equals(myContacts[i].getFirstname()) && ln.equals(myContacts[i].getLastname()))
				return myContacts[i].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 < size; i++)
		{
			//check if the current Contact is the one we're looking for
			if (fn.equals(myContacts[i].getFirstname()) && ln.equals(myContacts[i].getLastname()))
			{
				//shift all the elements down one
				for (int j = i; j < size-1; j++)
				{
					myContacts[j] = myContacts[j+1];
				}
				
				myContacts[size-1] = null;
				size--;
				return true;
			}
		}
		
		//if we get here, then we know that the Contact was never in the array, so we return false
		return false;
	}
}