import Shapes.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;

/**
 * MiniDraw
 * <p>
 *   <b>History</b> :
 *   <ul>
 *     <li>Version 0.3 : Migration to Java 1.5 : replace JFrame.show to JFrame.setVisible(true)
 *     <li>Version 0.2 : Minor modifications</li>
 *     <li>Version 0.1 : Initial version</li>
 *   </ul>
 * </p>
 * @author Pierrick Calvet & Florian Delclaux
 */
public class MiniDraw extends JFrame implements WindowListener{

/* Constants */
  final static int NOSHAPE = -1;
  final static int CIRCLE = 0;
  final static int ELLIPSE = 1;
  final static int SQUARE = 2;
  final static int RECTANGLE = 3;
  final static String DEFAULT_WIDTH = "100";
  final static String DEFAULT_HEIGHT = "50";
  final static int DEFAULT_SHAPE = CIRCLE;
  final static Color DEFAULT_COLOR = Color.blue;
  final static boolean DEFAULT_FILLED = false;

/* Different objects of the application */
  public MiniDraw_About about;
  public MiniDraw_Tools tools;
  public MiniDraw_Display display;
  public MiniDraw_StateBar statebar;
  
/* Variables */
  public boolean toSave = false;     /* If the design must be save or not : needn't to save at the start of application */

/**
 * Build MiniDraw
 */
  public MiniDraw() {
    getContentPane().setLayout(new BorderLayout());

    /* Menu Bar */
    MiniDraw_Menu menuBar = new MiniDraw_Menu(this);
    setJMenuBar(menuBar);

    /* Tools */
    tools = new MiniDraw_Tools(this);
    getContentPane().add(tools, "North");

    /* Display */
    display = new MiniDraw_Display(this);
    getContentPane().add(display, "Center");

    /* StateBar */
    statebar = new MiniDraw_StateBar();
    getContentPane().add(statebar, "South");

    /* About */
    about = new MiniDraw_About(this);

    setTitle("MiniDraw - Untitled");
    setSize(1024, 768);

    setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    setLocationRelativeTo(null);                  /* Place frame at center of screen */
    addWindowListener(this);
    setVisible(true);                                       /* Show frame */
  }

/**
 * Open a JFileChooser, load a file and fill shapes Vector.
 */
  public boolean loadFile(){
    JFileChooser chooser = new JFileChooser("..");
    chooser.setDialogTitle("Load");
    chooser.setApproveButtonText("Load");
    
    /* If all except load are click : exit method */
    if(chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
      return false;


    try {
      BufferedReader buff = new BufferedReader(new FileReader(chooser.getSelectedFile().getPath()));  /* Read file and put it into buffer */

      for(String line = buff.readLine(); line != null; line = buff.readLine()) {                      /* Read the buffer line by line */
        StringTokenizer t = new StringTokenizer(line, " ");
        Vector tmp = new Vector();

        while(t.hasMoreTokens())              /* Get all parameters from current line */
          tmp.add(t.nextToken());

        OurShape shapeTmp;

        switch((new Integer((String)tmp.elementAt(0))).intValue()) {
          /* Circle */
          case CIRCLE :
            shapeTmp = new OurCircle(new Integer((String)tmp.elementAt(1)).intValue(),
                                     new Integer((String)tmp.elementAt(2)).intValue(),
                                     new Integer((String)tmp.elementAt(3)).intValue());
            break;

          /* Ellipse */
          case ELLIPSE :
            shapeTmp = new OurEllipse(new Integer((String)tmp.elementAt(1)).intValue(),
                                      new Integer((String)tmp.elementAt(2)).intValue(),
                                      new Integer((String)tmp.elementAt(3)).intValue(),
                                      new Integer((String)tmp.elementAt(4)).intValue());
            break;

          /* Square */
          case SQUARE :
            shapeTmp = new OurSquare(new Integer((String)tmp.elementAt(1)).intValue(),
                                     new Integer((String)tmp.elementAt(2)).intValue(),
                                     new Integer((String)tmp.elementAt(3)).intValue());
            break;

          /* Rectangle */
          case RECTANGLE :
            shapeTmp = new OurRectangle(new Integer((String)tmp.elementAt(1)).intValue(),
                                        new Integer((String)tmp.elementAt(2)).intValue(),
                                        new Integer((String)tmp.elementAt(3)).intValue(),
                                        new Integer((String)tmp.elementAt(4)).intValue());
            break;

          default :
            JOptionPane.showMessageDialog(this,"Contains of file is erroned", "Error during read from file", JOptionPane.ERROR_MESSAGE);
            return false;
        }
        shapeTmp.setColor(new Color(new Integer((String)tmp.elementAt(5)).intValue(),
                                    new Integer((String)tmp.elementAt(6)).intValue(),
                                    new Integer((String)tmp.elementAt(7)).intValue()));                   /* Color's parameters */
        shapeTmp.setFilled((new Boolean((String)tmp.elementAt(8))).booleanValue());                       /* Filled parameter */
        display.shapes.add(shapeTmp);                                                                     /* Add to shapes vector */
      }
      display.repaint();                /* Repaint */
      buff.close();						          /* Close the buffer */
    }
    catch(IOException e){
      JOptionPane.showMessageDialog(this, e.getMessage());    /* Show errors */
      return false;
    }
    setTitle("MiniDraw - " + chooser.getSelectedFile().getName());                                  /* Change title of the application */
    return true;
  }

/**
 * Open a JFileChooser and save to file from shapes Vector.
 */
  public boolean saveFile(){

    JFileChooser chooser = new JFileChooser("..");
    chooser.setDialogTitle("Save");
    chooser.setApproveButtonText("Save");
    
    /* If all except save are click : exit method */
    if(chooser.showOpenDialog(this) != JFileChooser.APPROVE_OPTION)
      return false;

    try {
      BufferedWriter buff = new BufferedWriter(new FileWriter(chooser.getSelectedFile().getPath()));		/* Create a new buffer to write on it */

      for(int i = 0; i < display.shapes.size(); i++) {                  /* Cover the shapes vector */
        OurShape tmpShape = (OurShape)display.shapes.elementAt(i);
        String strType = new String();

        /* Determinate sort of shape */
        if(tmpShape instanceof OurRectangle)
          strType = "3";
        if(tmpShape instanceof OurSquare)
          strType = "2";
        if(tmpShape instanceof OurEllipse)
          strType = "1";
        if(tmpShape instanceof OurCircle)
          strType = "0";


        /* Create a string with all shape's parameters */
        String strShape = new String(strType + " " + tmpShape.x + " " + tmpShape.y + " " + tmpShape.width + " " + 
																		 tmpShape.height + " " + tmpShape.color.getRed() + " " + tmpShape.color.getGreen() + " " +
                                     tmpShape.color.getBlue() + " " + tmpShape.filled);
        /* Write the string */
        buff.write(strShape, 0, strShape.length());
        buff.newLine();                     					/* Create new line */
      }
      buff.close();                     							/* Close buffer */
    }
    catch(IOException e){
      JOptionPane.showMessageDialog(this, e.getMessage());  /* Show errors */
      return false;
    }
    setTitle("MiniDraw - " + chooser.getSelectedFile().getName());                                /* Change title of the application */
    return true;
  }

/*
 * main
 */
  public static void main(String args[]){
    try{
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    }
    catch(Exception e) { }

    MiniDraw miniDraw = new MiniDraw();
  }

/**
 * Ask to save art before exit application
 */
  public void windowClosing(WindowEvent e ){
    if(toSave){
      int ans = JOptionPane.showConfirmDialog(this, "Save your design ?", "Warning", JOptionPane.YES_NO_CANCEL_OPTION);

      if(ans == JOptionPane.CANCEL_OPTION)            /* Abort closing */
        return;

      if(ans == JOptionPane.YES_OPTION)               /* Ok to save */
        if (!saveFile())                              /* Save operation abort */
          return;

    }
    System.exit(0);
  }

  public void windowOpened(WindowEvent e ){}
  public void windowClosed(WindowEvent e ){}
  public void windowIconified(WindowEvent e ){}
  public void windowDeiconified(WindowEvent e ){}
  public void windowActivated(WindowEvent e ){}
  public void windowDeactivated(WindowEvent e ){}
}
