/* $Id: SpreadTreePanel.java 685 2013-03-18 17:32:14Z shayashi $ */
package smart_gs.swingui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.util.Enumeration;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import smart_gs.logical.GSResource;
import smart_gs.logical.Spread;
import smart_gs.logical.SpreadTree;
import smart_gs.smleditor.swingui.GSEditor;
import smart_gs.swingui.toolbar.action.NewCompactEditorAction;
import smart_gs.swingui.toolbar.action.NewEditorAction;

@SuppressWarnings("serial")
public class SpreadTreePanel extends JPanel implements MouseListener {
//public class SpreadTreePanel extends JPanel{
	
	private SpreadTree tree;
	private JScrollPane scrollPane;
	
	public SpreadTreePanel(){
		this.setLayout(new BorderLayout());
		scrollPane = new JScrollPane();
		setAutoscrolls(true);
		scrollPane.getVerticalScrollBar().setUnitIncrement(20);
		this.tree = SpreadTree.getInstance();
		JPanel panel = new JPanel();
		panel.setLayout(new BorderLayout());
		JPanel tree_panel = new JPanel();
		tree_panel.setLayout(new FlowLayout(FlowLayout.LEFT));
		tree_panel.setBackground(Color.white);
		tree_panel.add(tree);
		tree_panel.setBorder(BorderFactory.createLineBorder(Color.BLACK,2));
		tree.addMouseListener(this);
		
		JPanel button_panel = new JPanel();
		JButton windowbutton1 = new JButton("Compact Editor");
		windowbutton1.addActionListener(new NewCompactEditorAction());
		button_panel.add(windowbutton1);
		
		JButton windowbutton2 = new JButton("Editor");
		windowbutton2.addActionListener(new NewEditorAction());
		button_panel.add(windowbutton2);

		panel.add(tree_panel,BorderLayout.CENTER);

		scrollPane.setViewportView(panel);
		this.add(scrollPane,BorderLayout.CENTER);
		this.add(button_panel,BorderLayout.SOUTH);
	}
		
	public void mouseClicked(MouseEvent e) {
//		2011.03.07 shayashi changed
//		左クリックでSpreadを選択(double-click) or Spread Tree の　selection model へイベントを渡す(single-click)。
		if(e.getButton() == 1){
			Spread spread;
			if(e.getClickCount() == 2){
				GSResource selected;
				tree.expandRow(0);
				TreePath[] paths = this.tree.getSelectedPaths();
				if (paths != null && paths.length !=0) {
					selected = (GSResource)((DefaultMutableTreeNode)paths[0].getLastPathComponent()).getUserObject();
				} else return;				
				if (selected instanceof Spread) {
					 spread = (Spread)selected;
				} else {
					return;
				}
				if(spread != null){
					File imageFile = spread.getImageFile();
					System.out.println(imageFile);
					if (!imageFile.exists()) {
						JOptionPane.showMessageDialog(null,
								"Image File for the spread does not exist: " + imageFile.toString());
//						return;
					}
					WorkspaceWindow.getInstance().setSpread(spread);
					
				}
			} else if (e.getClickCount() == 1){
				tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION);
				//Alternative of right-click for Mac
				if(e.isAltDown()){
					JPopupMenu menu = new SpreadSelectPopupMenu(this.tree);
					menu.show(e.getComponent(),e.getX(),e.getY());
				} 
			}
			return;
		}
		
		//右クリックでシートを選択
		if(e.getButton() == 3){
			JPopupMenu menu = new SpreadSelectPopupMenu(this.tree);
			menu.show(e.getComponent(),e.getX(),e.getY());
		}
	}
	
	public void search(String q){
		startSearchTree(this.tree,this.tree.getPathForRow(0),q);
	}
	
	public Spread getSpreadInTree(int row){
		List list = this.tree.getSpreads();
		try{
			for(int i=0;i<list.size();i++){
				Spread spread = (Spread)list.get(i);
				if(spread.getPageViewIndex() == row){
					return spread;
				}
			}
		}catch(Exception e){
			return null;
		}
		return null;
	}
	
	public SpreadTree getTree(){
    	return tree;
    }
	public void mouseEntered(MouseEvent arg0) {
	}

	public void mouseExited(MouseEvent arg0) {
	}

	public void mousePressed(MouseEvent e) {
//		2011.03.08 shayashi comments out.
//		TreePath path = this.tree.getClosestPathForLocation(e.getPoint().x,e.getPoint().y);
//		this.tree.setSelectionPath(path);
	}

	public void mouseReleased(MouseEvent arg0) {
	}
	
	private void startSearchTree(JTree tree, TreePath path, String q){
		this.tree.clearSelection();
		searchTree(tree,path,q);
		// scrollPane.getVerticalScrollBar().setValue();
	}

	private void searchTree(JTree tree, TreePath path, String q) {
        TreeNode node = (TreeNode)path.getLastPathComponent();
        if(node==null){
        	return;
        }
        if(node.toString().equals(q)){
          tree.addSelectionPath(path);
        }
        if(!node.isLeaf() && node.getChildCount()>=0) {
            Enumeration e = node.children();
            while(e.hasMoreElements())
              searchTree(tree, path.pathByAddingChild(e.nextElement()), q);
        }
    }
}
