/*
 * MiningMart Version 1.0
 * 
 * Copyright (C) 2006 Martin Scholz, Timm Euler, 
 *                    Daniel Hakenjos, Katharina Morik
 *
 * Contact: miningmart@ls8.cs.uni-dortmund.de
 *
 * A list of contributing developers (other than the copyright 
 * holders) can be found at
 * http://mmart.cs.uni-dortmund.de/downloads/download.html
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program, see the file MM_HOME/LICENSE; if not, write
 * to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
 * Floor, Boston, MA 02110-1301, USA.
 */
package edu.udo.cs.miningmart.gui.application;


import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

import org.jhotdraw.framework.DrawingEditor;
import org.jhotdraw.framework.JHotDrawRuntimeException;
import org.jhotdraw.framework.Tool;
import org.jhotdraw.standard.AbstractTool;
import org.jhotdraw.util.Iconkit;
import org.musoft.limo.application.MyToolButton;
import org.musoft.limo.application.Resource;
import org.musoft.limo.application.StaticJButton;
import org.musoft.limo.application.ToolBar;
import org.musoft.limo.model.ModelFigureElement;

import edu.udo.cs.miningmart.exception.M4Exception;
import edu.udo.cs.miningmart.gui.model.MiningMartCase;
import edu.udo.cs.miningmart.gui.model.MiningMartChain;
import edu.udo.cs.miningmart.gui.model.MiningMartStep;
import edu.udo.cs.miningmart.gui.model.StepTransition;
import edu.udo.cs.miningmart.m4.M4Interface;
import edu.udo.cs.miningmart.m4.Operator;
import edu.udo.cs.miningmart.m4.OperatorGroup;
import edu.udo.cs.miningmart.m4.utils.Print;

/**
 * A Panel for preferred operators.
 * @author Daniel Hakenjos
 * @version $Id: OperatorToolPanel.java,v 1.4 2006/05/05 07:39:54 euler Exp $
 */
public class OperatorToolPanel extends ToolBar{

	private MiningMartApplication app;

	private JPanel op_panel,stuff_panel, panel, panel2,toppanel;
	private JScrollPane scrollpane;
	private JLayeredPane layerpane;
	private Vector opsintoolpanel;
	
	/**
	 * Constructor for OperatorToolPanel.
	 */
	public OperatorToolPanel(MiningMartApplication app) {
		super(app);

		this.app=app;
		initOperatorsInToolPanel();
		initComponents();		
		
		
	}
	
	private void initOperatorsInToolPanel(){
		opsintoolpanel=app.getOperatorsInToolPanel();
	}
	
	private void initComponents(){
		
		
		initStuffPanel();	
		initOperatorPanel();

		op_panel=new JPanel();
		GridLayout grid=new GridLayout(this.groupstoolbars.size(),1);
		grid.setHgap(4);
		grid.setVgap(4);
		op_panel.setLayout(grid);
		

		for (int index=0;index<this.groupstoolbars.size();index++){
			
			String groupname=(String) this.groups.get(index);

			ToolBar toolbar=(ToolBar) groupstoolbars.get(index);
			toolbar.addGroup(groupname);
			toolbar.showGroup(groupname,ToolBar.ACTIVE);
			
			toolbar.setPreferredSize(new Dimension(40,40));
			toolbar.setFloatable(false);
			op_panel.add(toolbar);

		}		
		panel2=new JPanel();
		panel2.setLayout(new BorderLayout());
		panel2.add(op_panel,BorderLayout.NORTH);	
		
		
		scrollpane=new JScrollPane(panel2);
		
		toppanel=new JPanel(){
			public String toString(){
				return Resource.getString("COMP_OPERATORTOOLS");
			}
		};
		toppanel.setLayout(new BorderLayout());
		toppanel.add(scrollpane,BorderLayout.CENTER);
		
	}
	
	private void initStuffPanel(){
		// use a Mediatracker to ensure that all the images are initially loaded
		Iconkit kit = Iconkit.instance();
		if (kit == null) {
			throw new JHotDrawRuntimeException("Iconkit instance isn't set");
		}

		//MiningMartChain erzeugen
		Tool tool =new MyAbstractTool(Resource.getString("TOOL_CHAIN"),app){
			public void mouseDown(MouseEvent e, int x, int y) {
				super.mouseDown(e, x, y);
				ModelFigureElement p = getPotentialParent(x, y, drawing());
				
				MiningMartChain s = null;
				
				if (p instanceof MiningMartCase){

					s = ((MiningMartCase) p).createMiningMartChain(p,Resource.getString("CHAIN"), new Point(x,y), new Rectangle(x,y,35,35));
				}
				else if (p instanceof MiningMartChain){

					s = ((MiningMartChain) p).createMiningMartChain(p,Resource.getString("CHAIN"), new Point(x,y), new Rectangle(x,y,35,35));
				}
				else{
					//offensichtlich liegt ein Fehler vor
					return;
				}
				editor().toolDone();
				if (s != null){
					app.selectFigure(s);
					M4Interface.print.doPrint(Print.COMPILER_CASE_CONTROL,Resource.getString("INSERTED_NEW_CHAIN")+" "+s.getName());
				}
			}
		}; 
		MyToolButton button=createMyToolButton(Resource.getString("TOOLIMG_CHAIN"), Resource.getString("TOOL_CHAIN"), tool);
		button.setToolTipText(Resource.getString("TOOL_CHAIN"));
		this.add("tools",button);

		//Merge to chain
		JButton jbutton = new StaticJButton(Resource.getString("TOOL_MERGE_CHAIN"), new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG1_MERGE_CHAIN"))));
		jbutton.setPressedIcon(new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG2_MERGE_CHAIN"))));
		jbutton.setBorder(null);
		jbutton.addMouseListener(
		new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				if (((StaticJButton)evt.getSource()).isEnabled())
					((MiningMartApplication) parent).promptMergeChain();
			}
		});
		jbutton.setToolTipText(Resource.getString("TOOL_MERGE_CHAIN"));
		this.add("tools", jbutton);

		//Unmerge to chain
		jbutton = new StaticJButton(Resource.getString("TOOL_UNMERGE_CHAIN"), new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG1_UNMERGE_CHAIN"))));
		jbutton.setPressedIcon(new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG2_UNMERGE_CHAIN"))));
		jbutton.setBorder(null);
		jbutton.addMouseListener(
		new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				if (((StaticJButton)evt.getSource()).isEnabled())
					((MiningMartApplication) parent).promptUnmergeChain();
			}
		});
		jbutton.setToolTipText(Resource.getString("TOOL_UNMERGE_CHAIN"));
		this.add("tools", jbutton);

		// StepTransition erzeugen   
		tool = new StepTransitionTool((MiningMartApplication) parent, StepTransition.class, MiningMartStep.class, "outgoing", MiningMartStep.class, "incoming");		
		add("tools", createMyToolButton(Resource.getString("TOOLIMG_TRANSITION"), Resource.getString("TOOL_TRANSITION"), tool));


		//Zeige alle vohandenen Transitionen
		jbutton = new StaticJButton(Resource.getString("TOOL_ALL_TRANSITIONS"), new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG1_ALL_TRANSITIONS"))));
		jbutton.setPressedIcon(new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG2_ALL_TRANSITIONS"))));
		jbutton.setBorder(null);
		jbutton.addMouseListener(
		new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				if (((StaticJButton)evt.getSource()).isEnabled())
					((MiningMartApplication) parent).promptShowAllTransitions();
			}
		});
		jbutton.setToolTipText(Resource.getString("TOOL_ALL_TRANSITIONS"));
		this.add("tools", jbutton);

		//Zeige die stepsettings
		jbutton = new StaticJButton(Resource.getString("TOOL_SHOW_STEPSETTINGS"), new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG1_SHOW_STEPSETTINGS"))));
		jbutton.setPressedIcon(new ImageIcon(kit.loadImageResource(Resource.getString("TOOLIMG2_SHOW_STEPSETTINGS"))));
		jbutton.setBorder(null);
		jbutton.addMouseListener(
		new java.awt.event.MouseAdapter() {
			public void mouseClicked(java.awt.event.MouseEvent evt) {
				if (((StaticJButton)evt.getSource()).isEnabled())
					((MiningMartApplication) parent).showStepSettings();
			}
		});
		jbutton.setToolTipText(Resource.getString("TOOL_SHOW_STEPSETTINGS"));
		this.add("tools", jbutton);
		
		
	}


	private void initOperatorPanel(){
		M4Interface m4i = M4Interface.getInstance();
		boolean success = true;
		if (m4i != null) {
			OperatorGroup opg = m4i.getOperatorGroup();
			Iterator it = opg.getTopLevelOperatorGroups().iterator();
			while (it.hasNext()) {
				Long opgId = (Long) it.next();
				try {
					this.recurseThroughInsertOps(opgId, opg);
				} catch (M4Exception e) {
					M4Interface.print.doPrint(Print.ERROR,e.getMessage(),e);
					success = false;
				}
			}
		}
		
	}	
	
	
	private void recurseThroughInsertOps(Long opGroupId, OperatorGroup opg) throws M4Exception {
		// the opGroupId belongs to an operator group (inner node), so just create
		// an according folder:
		//String name = opg.getGroupName(opGroupId);
		//IconCommandMenu cclist = this.getInsertItemFolder(name);

		// Iterate through the contained elements:
		Collection col = opg.getChildGroups(opGroupId);
        /*
         * Joerg, 2006-05-03: Check for null value.
         */
        if (col != null) {
    		Iterator it = col.iterator();
    		while (it.hasNext()) {
    			Long idNext = (Long) it.next();
    
    			// Test whether idNext represents an inner node or an operator:
    			Collection down = (Collection) opg.getChildGroups(idNext);
    			if (down != null) { 
    				// "down" represents an inner node, recurse!
    				this.recurseThroughInsertOps(idNext, opg);
    			} else { 
    				// "down" represents an operator, just add it to the folder!
    				Operator op = (edu.udo.cs.miningmart.m4.Operator) opg.getOperator(idNext);
    				if (op != null) {
    					String opName = op.getName();
    					String groupname=opg.getGroupName(opGroupId);
    					addOperatorToolButton(opName,groupname);
    				}
    			}
    		}
        }
	}
	
	private void addOperatorToolButton(String opname,String groupname){
		Tool tool;
		MyToolButton button;
		
		if (opsintoolpanel.contains(opname.toLowerCase())){

			tool = new MyAbstractTool(opname,app) {
			public void mouseDown(MouseEvent e, int x, int y) {
				super.mouseDown(e, x, y);
				
//				M4Interface.print.doPrint(Print.MAX,"New Operator-Menu-Item  inserted for Operator: "+this.getName());
		
				ModelFigureElement p = app.getPotentialParent(x, y);
				
				MiningMartStep s = null;
				
				if (p instanceof MiningMartChain){

					s = ((MiningMartChain) p).createMiningMartStep(p,this.getName(),new Point(x,y),new java.awt.Rectangle(x, y, 35, 35));
				}
				else{
					//nur bei Chain duerfen Steps hinzugef?gt werden
					return;
				}
				//editor().toolDone();
				app.toolDone();
				if (s != null){
					app.selectFigure(s);
					M4Interface.print.doPrint(Print.COMPILER_CASE_CONTROL,Resource.getString("INSERTED_OPERATOR")+" "+s.getName());
				}
				
			}
		};
		button=createMyToolButton(Resource.getString("TOOLIMG_GENERIC"),Resource.getString(opname), tool);
		button.setToolTipText(opname);
		this.add(groupname,button);
		}
		
	}

	/**
	 * Adds a <code>JButton</code> with its groupname.
	 */
	public Component add(String groupname, JButton button){
		
		if (groups.contains(groupname)){
			int index=groups.indexOf(groupname);
			
			ToolBar bar=(ToolBar) groupstoolbars.remove(index);
			
			bar.addButton(groupname,button);
			
			groupstoolbars.insertElementAt(bar,index);
		}
		else{
			groups.add(groupname);
			
			ToolBar bar=new ToolBar(app);
			bar.removeAll();
			
			bar.addButton(groupname,button);
			
			groupstoolbars.add(bar);
		}	
		
		return button;
		
	}
	
	private Vector groups=new Vector();
	private Vector groupstoolbars=new Vector();

	/**
	 * Gets the <code>JPanel</code> with the preferred operators.
	 */
	public JPanel getOperatorToolPanel(){
		return this.toppanel;
	}
	
	private class MyAbstractTool extends AbstractTool{

		private String name;

		public MyAbstractTool(String name, DrawingEditor drawingeditor){
			super(drawingeditor);
			this.name=name;
		}
		
		public String getName(){
			return name;
		}
	}
	
}
/*
$Log: OperatorToolPanel.java,v $
Revision 1.4  2006/05/05 07:39:54  euler
Bugfix by Joerg Pleumann

Revision 1.3  2006/04/11 14:10:15  euler
Updated license text.

Revision 1.2  2006/04/06 16:31:15  euler
Prepended license remark.

Revision 1.1  2006/01/03 09:54:26  hakenjos
Initial version!

*/
