package sim;

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;

import sim.util.SimButton;
import sim.util.SimButtonListener;
import sim.util.DownloadDialog;
import sim.util.SimFileDialog;

public class SaveLoadShortcut extends Panel
{
	public static FileDialog FILEDIALOG;
	public static final GuiFileLink GUI_FILE_LINK = new GuiFileLink();
	
	private SaveLoadShortcutListener listener;
	
	public SaveLoadShortcut()
	{
		super();
		this.setLayout(new FlowLayout(FlowLayout.LEFT, 8, 0));
	}
	
	public void addNotify()
	{
		super.addNotify();
		this.listener = new SaveLoadShortcutListener(this);
	}
	
	public void setEnabled(boolean b)
	{
		MainWindow.MENU.NEW.setEnabled(b);
		MainWindow.MENU.OPEN.setEnabled(b);
		
		if(MainWindow.MASTER == null)
		{
			MainWindow.MENU.SAVE_AS.setEnabled(b);
			MainWindow.MENU.SAVE.setEnabled(b);
		}
		
		this.listener.setEnabled(b);
	}
	
/* ==================================================================
	Services provided to Menu
	================================================================ */
	public void createNew()
	{
		this.listener.createNew("Untitled.toy");
	}
	
	public void save()
	{
		this.listener.save();
	}
	
	public void saveAs()
	{
		this.listener.saveAs();
	}
		
	public void load()
	{
		this.listener.load();
	}
	
/* ==================================================================
	Listener to handle mouse events
	================================================================= */
	public class SaveLoadShortcutListener extends SimButtonListener
	{
		private SimButton create;
		private SimButton save;
		private SimButton load;
		private DownloadDialog remoteDialog;
		private boolean buttonUpOnLastMouseDown;
		
		public SaveLoadShortcutListener(SaveLoadShortcut parent)
		{
			Panel p = new Panel(new FlowLayout(FlowLayout.LEFT, 0, 0));
			parent.add(p);
			
			this.buttonUpOnLastMouseDown = true;
			
			this.create = new SimButton("sim/images/New.gif", "New", NorthPanel.BUBBLE_WAIT);
			this.create.setListener(this);
			p.add(this.create);
			
			this.save = new SimButton("sim/images/Save.gif", "Save", NorthPanel.BUBBLE_WAIT);
			this.save.setListener(this);
			p.add(this.save);
			
			this.load = new SimButton("sim/images/Open.gif", "Load", NorthPanel.BUBBLE_WAIT);
			this.load.setListener(this);
			p.add(this.load);
			
			if(MainWindow.MASTER == null)
				SaveLoadShortcut.FILEDIALOG = new SimFileDialog(MainWindow.MAIN_WINDOW);
			else
			{
				this.save.setEnabled(false);
				this.remoteDialog = new DownloadDialog(MainWindow.MASTER.getCodeBase().toString());
			}
		}
		
		public void setEnabled(boolean b)
		{
			this.create.setEnabled(b);
			this.load.setEnabled(b);
			
			if(MainWindow.MASTER == null)
				this.save.setEnabled(b);
		}
		
		public void actionPerformed(ActionEvent e)
		{
			SimButton ib = (SimButton)e.getSource();
			if(ib == this.create)
			{
				this.create.paintRaised();
				this.createNew("Untitled.toy");
			}
			else if(ib == this.save)
			{
				this.save.paintRaised();
				this.save();
			}
			else if(ib == this.load)
			{
				this.load.paintRaised();
				this.load();
			}
		}
		
		public void activate(SimButton ib)
		{
			ib.processActionEvent();
			ib.setArmed(false);
		}
		
		public void arm(SimButton ib)
		{
			ib.setArmed(true);
		}
		
		public void disarm(SimButton ib)
		{
			ib.setArmed(false);
		}
		
		public void mousePressed(MouseEvent event)
		{
			SimButton ib = (SimButton)event.getSource();
			if(ib.isEnabled())
			{
				ib.paintInset();
				this.buttonUpOnLastMouseDown = ib.isRaised();
				this.arm(ib);
			}
		}
	
		public void mouseClicked(MouseEvent event)
		{
			SimButton ib = (SimButton)event.getSource();
			if(ib.isEnabled() && ib.isArmed())
				this.activate(ib);
		}
		
		public void mouseReleased(MouseEvent event)
		{
			SimButton ib = (SimButton)event.getSource();
			Point pt = event.getPoint();
			
			if(ib.contains(pt.x, pt.y))
				this.mouseClicked(event);
		}
		
		public void mouseDragged(MouseEvent event)
		{
			SimButton ib = (SimButton)event.getSource();
			if(ib.isEnabled() && ib.isArmed())
			{
				Point loc = event.getPoint();
				
				if(ib.contains(loc.x,loc.y))
				{
					if(this.buttonUpOnLastMouseDown)
					{
						if( ! ib.isRaised()) 
							ib.paintRaised();
					}
					else
						if(ib.isRaised())
							ib.paintInset();
				}
				else
				{
					if(this.buttonUpOnLastMouseDown)
						{
						if(ib.isRaised())
							ib.paintInset();
					}
					else
						if( ! ib.isRaised())
							ib.paintRaised();
				}
			}
		}
		
		public void createNew(String fileName)
		{
			if(!CentralPanel.ACTIVE_GRID.isModified())
			{
				MainWindow.MAIN_WINDOW.setCursor(Cursor.WAIT_CURSOR);
				MainWindow.CENTRAL_PANEL.createGrid(fileName);
				NorthPanel.GRID_SHORTCUT.setGridVisibility(true);
				NorthPanel.GRID_SHORTCUT.setZoom("100%");
				MainWindow.MAIN_WINDOW.setCursor(Cursor.DEFAULT_CURSOR);
			}
			else
			{
				// prompt the user with (do u want to save changes?)
				// if cancel then cancel
				// else save and call this function again
			}
		}
		
		public void save()
		{
			MainWindow.MAIN_WINDOW.setCursor(Cursor.WAIT_CURSOR);
			
			try
			{
				if(WestPanel.MODE_CONTROL.getCurrnetActive() != WestPanel.MODE_CONTROL.getEditButton())
					WestPanel.MODE_CONTROL.switchToEditMode();
				else
					WestPanel.MODE_CONTROL.getEditHandler().deselect(true);
				
				String outFile = CentralPanel.ACTIVE_GRID.getName();
				
				try
				{
					BufferedWriter outStream = new BufferedWriter(new FileWriter(outFile));
					SaveLoadShortcut.GUI_FILE_LINK.save(outStream, CentralPanel.ACTIVE_GRID);
					outStream.close();
				}
				catch(IOException e)
				{
					throw (new SimException("can not open file"));
				}
			}
			catch(SimException exc)
			{
				MainWindow.OK_WINDOW.setDescription("Exception occur during saving");
				MainWindow.OK_WINDOW.setMessage(exc.getMessage());
				MainWindow.OK_WINDOW.show();
			}
			
			MainWindow.MAIN_WINDOW.setCursor(Cursor.DEFAULT_CURSOR);
		}
		
		public void saveAs()
		{
			MainWindow.MAIN_WINDOW.setCursor(Cursor.WAIT_CURSOR);
			
			try
			{
				if(WestPanel.MODE_CONTROL.getCurrnetActive() != WestPanel.MODE_CONTROL.getEditButton())
					WestPanel.MODE_CONTROL.switchToEditMode();
				else
					WestPanel.MODE_CONTROL.getEditHandler().deselect(true);
				
				SaveLoadShortcut.FILEDIALOG.setTitle("Save As");
				SaveLoadShortcut.FILEDIALOG.setMode(FileDialog.SAVE);
				SaveLoadShortcut.FILEDIALOG.setFile("*.toy");
				SaveLoadShortcut.FILEDIALOG.show();
				
				String outFile = SaveLoadShortcut.FILEDIALOG.getFile();
				
				if(outFile != null)
				{
					try
					{
						outFile = SaveLoadShortcut.FILEDIALOG.getDirectory() + outFile;
						BufferedWriter outStream = new BufferedWriter(new FileWriter(outFile));
						SaveLoadShortcut.GUI_FILE_LINK.save(outStream, CentralPanel.ACTIVE_GRID);
						outStream.close();
						CentralPanel.ACTIVE_GRID.setName(outFile);
						MainWindow.MAIN_WINDOW.setTitle(MainWindow.PROGRAM_NAME + " - " + outFile);
					}
					catch(IOException e)
					{
						throw (new SimException("can not open file"));
					}
				}
			}
			catch(SimException exc)
			{
				MainWindow.OK_WINDOW.setDescription("Exception occur during saving");
				MainWindow.OK_WINDOW.setMessage(exc.getMessage());
				MainWindow.OK_WINDOW.show();
			}
			
			MainWindow.MAIN_WINDOW.setCursor(Cursor.DEFAULT_CURSOR);
		}
		
		public void load()
		{
			MainWindow.MAIN_WINDOW.setCursor(Cursor.WAIT_CURSOR);
			
			try
			{
				Reader inStream;
				
				if(MainWindow.MASTER == null)
				{
					SaveLoadShortcut.FILEDIALOG.setTitle("Open");
					SaveLoadShortcut.FILEDIALOG.setMode(FileDialog.LOAD);
					SaveLoadShortcut.FILEDIALOG.setFile("*.toy");
					SaveLoadShortcut.FILEDIALOG.show();
					
					String inFile = SaveLoadShortcut.FILEDIALOG.getFile();
					
					if(inFile != null)
					{
						try
						{
							inFile = SaveLoadShortcut.FILEDIALOG.getDirectory() + inFile;
							this.createNew(inFile);
							inStream = new BufferedReader(new FileReader(inFile));
							SaveLoadShortcut.GUI_FILE_LINK.load(inStream, CentralPanel.ACTIVE_GRID);
							inStream.close();
							CentralPanel.ACTIVE_GRID.setName(inFile);
						}
						catch(IOException e)
						{
							throw (new SimException("can not open file"));
						}
					}
				}
				else
				{
					// handle internet dowloads
					this.remoteDialog.setVisible(true);
					
					String inFile =  this.remoteDialog.getFile();
					
					if(inFile != null)
					{
						try
						{
							this.createNew(inFile);
							inFile = this.remoteDialog.getURL() + inFile;
							inStream = new BufferedReader(new InputStreamReader((new URL(inFile)).openStream()));
							SaveLoadShortcut.GUI_FILE_LINK.load(inStream, CentralPanel.ACTIVE_GRID);
							inStream.close();
							CentralPanel.ACTIVE_GRID.setName(inFile);
						}
						catch(MalformedURLException mue)
						{
							throw (new SimException("URL does not exist"));
						}
						catch(IOException e)
						{
							throw (new SimException("can not open file"));
						}
					}
				}
			}
			catch(SimException exc)
			{
				MainWindow.OK_WINDOW.setDescription("Exception occur during loading");
				MainWindow.OK_WINDOW.setMessage(exc.getMessage());
				MainWindow.OK_WINDOW.show();
			}
			
			MainWindow.MAIN_WINDOW.setCursor(Cursor.DEFAULT_CURSOR);
		}
	}
}

