/*
   Tamot --- Task Modelling Editor
   Copyright (C) 2000 Commonwealth Scientific and Industrial Research Organisation
   (CSIRO), Australia. All rights reserved. 

   The Software, owned by CSIRO Australia, has been developed by the CSIRO 
   Intelligent Interactive Technology group. 
   For more information, please see http://www.cmis.csiro.au/iit/.

   The Software is a beta-test version for internal research and evaluation purposes 
   by the Licensee. The Software is still at a development stage. 
   It has not undergone complete testing and may have inherent errors,
   bugs or deficiencies that can affect the operation of the Software. 

   We encourage your feedback and suggestions. Any bugs / suggestions found please email to
   Shijian.Lu@cmis.csiro.au and Thomas.Lo@cmis.csiro.au. 

   After you have signed the Beta-Test Software License Agreement with the CSIRO,
   CSIRO grants you a non-exclusive, non-transferable license to use it only for your 
   personal, non-commercial and lawful end use. Implied licenses are negated. 

   Warranty Disclaimer : 

   CSIRO supplies the Software on an "as is" basis and makes no warranties that use of
   the Software by the Licensee will not infringe any third party’s 
   Intellectual Property Rights nor that the Software will be of merchantable quality,
   or suitable for a particular purpose. CSIRO excludes all terms, conditions and
   warranties implied by custom, the general law or statute in relation to the
   Software.
*/

package taskModellingTool;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import com.helplets.awt.PercentLayout;

/**
 * MainFrame contains every GUI components.
 * These components as well as the Manager are created in this within
 * this class, and won't be created any more since they are static.
 */
public class MainFrame extends JFrame {
    //Constants
    protected static final int FRAME_INSET=50;
    private static final float LEFT_RATIO=0.21f;
    protected static String TITLE_FIXED="Tasks Editor - ";
    protected static String TITLE_NEW="Untitled";
    protected static String TITLE_VARIABLE="Untitled";
    
    //Thomas
    //protected static final String LOGO="icons"+File.separator+"IsoldeLogo.jpg";
    protected static final String LOGO = 
    	ClassLoader.getSystemResource("icons"+File.separator+"IsoldeLogo.jpg").getFile();
    
    //Creation of the GUI constituents
    protected static MainTree tree;
    
    protected static GraphicDesktop desktop;
    protected static RTFPane editor;
    protected static GraphicToolBar graphicToolBar;
    protected static MainMenu menu;
    protected static JPopupMenu popup;
    protected static AttributesPanel attributesPanel;
    protected static MainFrame mainFrame;
    
    protected static JSplitPane editorSplitPane;
    protected static JSplitPane treeSplitPane;
    protected static JSplitPane globalSplitPane;
    
    protected static FootPane footPane;
    protected static Label mainFrameMessage;

    //And a manager to centralize the functions associated with every component in the GUI
    protected static Manager manager;
    
    //Thomas
    //private static final String USER="cfg"+File.separator+"user.cfg";
    private static final String USER=ClassLoader.getSystemResource("cfg"+File.separator+"user.cfg").getFile();
    
    private static ObjectInputStream userIn;
    private static ObjectOutputStream userOut;

    
//  public MainFrame(JProgressBar pbar) {
    public MainFrame() {
    	super(TITLE_FIXED+TITLE_VARIABLE);
        
    	JProgressBar pbar = Banner.pbar;
        
    	setVisible(false);    	    	    	
    	
        setIconImage(new ImageIcon(LOGO).getImage());
    	
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    	
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                if (Manager.fileSaved()) {
                    editor.closing();
                    closing();
                    System.exit(0);
                }
            }
        });
    	
    	JComponent contentPane = (JComponent)getContentPane();
    	
    	//The dimension of the frame is based on the screen's dimensions
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    	setBounds(FRAME_INSET,FRAME_INSET,
    		screenSize.width-FRAME_INSET*2,
    		screenSize.height-FRAME_INSET*2);
    	
    	pbar.setValue(1);
    	
    	//Add Menu
    	menu = new MainMenu();
    	setJMenuBar(menu);
    	
    	ProgramToolBar pt = new ProgramToolBar();
    	pt.setToolTipText("Program tool bar");
    	//pt.setSize(pt.getWidth(),25);
    	contentPane.add(pt,BorderLayout.NORTH);

    	pbar.setValue(2);
    	
    	//Add Tree and GraphicDesktop in a split panel
        
        // Task hierarchy
    	tree = new MainTree();
        
        JScrollPane mt = new JScrollPane(tree);
    	//JScrollPane mt = new JScrollPane(tree.displayTree);
        mt.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Task hierarchy"),BorderFactory.createBevelBorder(1)));
    	mt.setToolTipText("Click on the component you want to select in the 'Navigation desktop'");
        
        // Task attributes
        attributesPanel = new AttributesPanel();
        
    	JScrollPane ap = new JScrollPane(attributesPanel);
        ap.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Task attributes"),BorderFactory.createBevelBorder(1)));
    	ap.setToolTipText("Displayable attributes (chosen from the 'Components Options' menu)");
        
        // SplitPane between Task hierarchy & Task attributes
    	JSplitPane treeSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,mt,ap);
    	treeSplitPane.setOneTouchExpandable(true);
    	
    	pbar.setValue(3);
    	
    	treeSplitPane.setPreferredSize(new Dimension(
    	  Math.round((float)(screenSize.width-FRAME_INSET*2)*LEFT_RATIO),100));
          
        // Vertical toolbar
    	graphicToolBar = new GraphicToolBar();
    	graphicToolBar.setToolTipText(
    	    "To create composite task, you have to put a component inside this this task");
    	//graphicToolBar.setFloatable(false);

    	pbar.setValue(4);
    	
    	JPanel p = new JPanel();    	
    	p.setLayout(new BorderLayout());
    	p.add(graphicToolBar,BorderLayout.WEST);

        // Navigation desktop
        desktop = new GraphicDesktop();
        
    	JScrollPane scroll = new JScrollPane(desktop);
        scroll.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Navigation desktop"),
            BorderFactory.createBevelBorder(1)));
    	scroll.setToolTipText(
    	    "Click on a component to select it (a double click expands a composite component)");
    	
        // Commentary
    	editor = new RTFPane();
        
        editor.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createTitledBorder("Commentary"),BorderFactory.createBevelBorder(1)));
    	editor.setToolTipText(
    	    "Enter your commentary for the selected component (a component must be selected!)");
            
        // SplitPane between Navigation desktop and Commentary
    	editorSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,scroll,editor);
    	editorSplitPane.setOneTouchExpandable(true);
    	
    	pbar.setValue(5);
    	
    	p.add(editorSplitPane,BorderLayout.CENTER);
    	
    	JSplitPane globalSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,treeSplitPane,p);
    	try {
    	    userIn = new ObjectInputStream(new FileInputStream(USER));
    	    //globalSplitPane.setDividerLocation(userIn.readInt());
    	    //treeSplitPane.setDividerLocation(userIn.readInt());
    	    editorSplitPane.setDividerLocation(userIn.readInt());
    	    userIn.close();
    	} 
    	catch (Exception ex) {
    		//System.out.println("Unable to retrieve configuration!");
            System.out.println("[ "+ex.getMessage()+" ] : Unable to retrieve configuration!");
    	}
    	
    	contentPane.add(globalSplitPane,BorderLayout.CENTER);
   	
        popup = menu.getGraphicPanelPopup();
        popup.setVisible(false);

    	pbar.setValue(6);

    	
    	//Create the manager.
    	//The manager's methods and fields are static: we won't create an
    	//instance of Manager any more.

 /*   	
    	Panel borderPane = new Panel();
    	
    	GridBagLayout gridbag = new GridBagLayout();
        GridBagConstraints c = new GridBagConstraints();
    	
    	BorderLayout bl=new BorderLayout();
    	bl.setHgap(0);
   	    borderPane.setLayout(gridbag);
 	    borderPane.setFont(new Font("Times", Font.PLAIN, 8));
    	c.weightx = 1.0;
    	c.insets = new Insets(1, 1, 1, 1);
    	addLabel9( borderPane, gridbag, c); 
    	
    	c.gridwidth = GridBagConstraints.REMAINDER; //end row
        Label label10 = new Label("");
        gridbag.setConstraints(label10, c);
        borderPane.add(label10);      
              
     	c.gridx =0;
 		
  	    Label label1 = new Label("fsdfdsafdsafd");
    //	borderPane.add(label1,BorderLayout.WEST);
	    c.gridwidth = 1; 
        gridbag.setConstraints(label1, c);
        borderPane.add(label1);
    
    	c.gridx =1;
 		
  	    Label label2 = new Label("fsdfdsafdsafd");
    //	borderPane.add(label1,BorderLayout.WEST);
	    c.gridwidth = 1; 
        gridbag.setConstraints(label2, c);
        borderPane.add(label2);
  
    	c.gridx =2;
    	c.gridwidth = 15;//GridBagConstraints.REMAINDER;;
    	c.fill = GridBagConstraints.BOTH;
     	Button bt1= new Button("a Button");
        gridbag.setConstraints(bt1, c);
        borderPane.add(bt1);
 

    	Button bt1= new Button("a Button");
	    Label lab1 =new Label("");
       	borderPane.setLayout(new PercentLayout());
	    borderPane.add("left=1, right=20, top=20", lab1);
    	borderPane.add("left=20, right=99,top=20", bt1);
    //	borderPane.add("left=20, right=99,top=20", new  JProgressBar(0,10));
 
  
        footPane= new FootPane();
        footPane.add(lab1);
	    contentPane.add(footPane,BorderLayout.SOUTH);
    */
    /*	JProgressBar progressbar=new JProgressBar(0,10);
    	MainFrame.footPane.setLabelText("Openning file: ");
    	MainFrame.footPane.setComponent(progressbar);
    	progressbar.setValue(2);
    	    
    	progressbar.setValue(2);    	
    	progressbar.setValue(2);	
    	progressbar.setValue(2);
    */
    	
        // add a bottom margin
        mainFrameMessage = new Label("");
        mainFrameMessage.setAlignment(Label.LEFT) ;
        
        contentPane.add(mainFrameMessage,BorderLayout.SOUTH);

        manager = new Manager(true);
        
        mainFrame = this;
        
        setContentPane(contentPane);
        
    	pbar.setValue(7);
    }
        
    public static void closing() {
        try {
    	    userOut = new ObjectOutputStream(new FileOutputStream(USER));
    	    //userOut.writeInt(globalSplitPane.getDividerLocation());
    	    //userOut.writeInt(treeSplitPane.getDividerLocation());
    	    userOut.writeInt(editorSplitPane.getDividerLocation());
    	    userOut.close();
    	}
        catch (Exception ex) {}
    }
    
    
    public static void changeTitle() {
        MainFrame.mainFrame.setTitle(MainFrame.TITLE_FIXED + MainFrame.TITLE_VARIABLE);
	    System.out.println("Update "+MainFrame.TITLE_VARIABLE);
    }
     
    protected void addLabel9(JPanel jPane, GridBagLayout gridbag,GridBagConstraints c) {
        for (int i = 0; i<9; i++) {
            Label label = new Label("");
            gridbag.setConstraints(label, c);
            jPane.add(label);
        }
    }
    
    // select the first window in desktop after frame is visible 
    // to fix the bug after upgrade to JDK v.1.31
    public void selectFirstWindow() {
        manager.openChildFrame(tree.getPathForRow(0));
    }
    
    //shijian 2001-1-23
    public static MainFrame getMainFrame(){
    	
    	return mainFrame;
    }
    
}