/**
 * Title:
 * @version:    $Id: CloseableTabbedPane.java,v 1.1 2004/11/15 13:47:50 rob Exp $
 * Copyright:   Copyright (C) 2003 Ian Ibbotson
 * @author:     Ian Ibbotson
 * Company:
 * Description:
 */

package com.k_int.AdminApp.gui.ExplorerView;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


public class CloseableTabbedPane extends JTabbedPane 
{
    protected ImageIcon closingIcon;
    
    public CloseableTabbedPane(ImageIcon closingIcon) 
    {
	this.closingIcon = closingIcon;
	addMouseListener(new ClosingListener());
    }
    
    public CloseableTabbedPane(AdminController controller) 
    {
	// this(AdminMainFrame.getImage("16","remove.png"));
	this(controller.getImage("16","remove.png"));
    }

    public void addTab(String title, Component component, boolean closeable) 
    {
  	if (closeable) {
  	    super.addTab(title, new ClosingIcon(closingIcon), component);
	}
  	else {
  	    super.addTab(title, component);
	}
	setSelectedComponent(component);
    }

    public void addTab(String title, Component component) 
    {
	addTab(title, component, true);
    }

    //--- Inner Class(es) ---

    protected class ClosingListener extends MouseAdapter
    {
	
	public void mouseReleased(MouseEvent e)
	{
	    int i = getSelectedIndex();
	    
	    // nothing selected
	    if (i == -1)
		return;
	    
	    ClosingIcon icon = (ClosingIcon)getIconAt(i);
	    
	    // close tab, if icon was clicked
	    if (icon != null && icon.contains(e.getX(), e.getY())) {
                Component c = getComponentAt(i);
                if ( c instanceof Closeable )
                {
                  ((Closeable)c).close();
                }
                // We really need the controller to organise this for us
		// removeTabAt(i);
	    }
	}
	
    }

    protected class ClosingIcon implements Icon
    {
	private Icon icon;    
	private int x = 0;
	private int y = 0;
	private int height = 10;
	private int width = 10;

	public ClosingIcon(ImageIcon icon)
	{
	    this.icon = icon;

	    if (icon != null) {
		height = icon.getIconHeight();
		width = icon.getIconWidth();
	    }
	}
	
	public int getIconHeight()
	{
	    return height;
	}

	public int getIconWidth()
	{
	    return width;
	}

	public void paintIcon(Component c, Graphics g, int x, int y)
	{
	    this.x = x;
	    this.y = y;
	    
	    if (icon != null) {
		icon.paintIcon(c, g, x, y + 1);
	    }
	    else {
		g.drawRect(x, y + 1, width, height);
	    }
	}    
	
	public boolean contains(int xEvent, int yEvent)
	{
	    if (!(xEvent >= x) || !(xEvent <= x + width)) {
		return false;
	    }
	    if (!(yEvent >= y) || !(yEvent <= y + height)) {
		return false;
	    }

	    return true;
	}
    }
}
