package pex07;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFileChooser;


public class Controller implements ActionListener
{
	private View view;
	private Model model;
	private JFileChooser chooser;
	
	public Controller(View view, Model model)
	{
		this.view = view;
		this.model = model;
		this.chooser = new JFileChooser();
	}
	
	public void actionPerformed(ActionEvent event)
	{
		String command = event.getActionCommand();
		if(command.equals(View.ADD))
		{
			// Try to create a person from the user input age and name
			String name = this.view.getPersonName();
			if(!name.isEmpty())
			{
				try 
				{
					int age = this.view.getAge();
					Person p = new Person(name, age);
					// Here's the new person; add them to the model
					this.model.put(name, p);
				}
				catch(NumberFormatException x)
				{
				}
			}
		}
		else if(command.equals(View.EXIT))
		{
			this.view.setVisible(false);
			this.view.dispose();
		}
		else if(command.equals(View.FIND))
		{
			// Try to find the person with the name supplied by
			// the user.
			String name = this.view.getPersonName();
			if(!name.isEmpty())
			{
				Person p = this.model.get(name);
				if(p != null)
				{
					// Found a person with this name; show the age.
					this.view.setAge(p.getAge());
				}
			}
		}
		else if(command.equals(View.OPEN))
		{
			int returnVal = chooser.showOpenDialog(this.view);
		    if(returnVal == JFileChooser.APPROVE_OPTION) 
		    {
		    	File f = chooser.getSelectedFile();
		    	try
		    	{
		    		FileInputStream fin = new FileInputStream(f);
		    		ObjectInputStream oin = new ObjectInputStream(fin);
		    		Model newModel = new Model(oin);
		    		this.model = newModel;
		    		this.view.setCount(this.model.size());
		    	}
		    	catch(Exception x)
		    	{
		    		System.out.println("open failed " + x.getMessage());
		    	}
		    }
		}
		else if(command.equals(View.SAVE))
		{
			int returnVal = chooser.showSaveDialog(this.view);
		    if(returnVal == JFileChooser.APPROVE_OPTION) 
		    {
		    	File f = chooser.getSelectedFile();
		    	try
		    	{
		    		FileOutputStream fout = new FileOutputStream(f);
		    		ObjectOutputStream oout = new ObjectOutputStream(fout);
		    		oout.writeObject(this.model);
		    	}
		    	catch(Exception x)
		    	{
		    	}
		    }
		}
		else if(command.equals(View.PRINT))
		{
			System.out.println(this.model.getMap());
		}
	}
}
