/*
 * Copyright 
 *   2005 axYus - www.axyus.com
 *   2005 C.Marchand - christophe.marchand@axyus.com
 * 
 * This file is part of XEMELIOS.
 * 
 * XEMELIOS 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.
 * 
 * XEMELIOS 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 XEMELIOS; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

package fr.gouv.finances.cp.xemelios.ui;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuItem;

import org.apache.log4j.Logger;

import fr.gouv.finances.cp.utils.ui.IhmFactory;

/**
 * Un menu "Fenetre" a la windows
 * @author chm
 */
public class WindowMenu extends JMenu {
    private static Logger logger = Logger.getLogger(WindowMenu.class);
    private JMenuItem[] cstMenus=null;
    private static Icon flagIcon = IhmFactory.getIconFromResource(ImageResources.FLAG_MENU);
    /**
     * Comment for <code>serialVersionUID</code>
     */
    private static final long serialVersionUID = 3257572810372100920L;
    /**
     * Le desktop pour lequel on cree le menu
     */
    private JDesktopPane desk = null;

    /**
     * 
     */
    public WindowMenu(JDesktopPane desk) {
        super();
        this.desk = desk;
        initialize();
    }
    /**
     * @param s
     */
    public WindowMenu(String s, JDesktopPane desk) {
        super(s);
        this.desk = desk;
        initialize();
    }
    /**
     * @param a
     */
    public WindowMenu(Action a, JDesktopPane desk) {
        super(a);
        this.desk = desk;
        initialize();
    }
    /**
     * @param s
     * @param b
     */
    public WindowMenu(String s, boolean b, JDesktopPane desk) {
        super(s, b);
        this.desk = desk;
        initialize();
    }

    private void initialize() {
        cstMenus = new JMenuItem[3];
        cstMenus[0] = new JMenuItem("Cascade");
        cstMenus[0].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                cascade(desk);
            }
        });
        cstMenus[1] = new JMenuItem("Mosaïque");
        cstMenus[1].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                tile(desk);
            }
        });
        cstMenus[2] = new JMenuItem("Tout réduire");
        cstMenus[2].addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
//                DesktopManager dm = desk.getDesktopManager();
                for(JInternalFrame frame:desk.getAllFrames()) {
                    try {
                        frame.setIcon(true);
                    } catch(Throwable t) {}
                }
            }
        });
    }
    @Override
    public void menuSelectionChanged(boolean isIncluded) {
        if(isIncluded) {
            showWindowMenu();
        }
        super.menuSelectionChanged(isIncluded);
    }
    private void showWindowMenu() {
        if(desk==null) {
            logger.error("desk is null !");
            return;
        }
        JInternalFrame[] frames = desk.getAllFrames();
        removeAll();
        reAddMenus(frames);
        for(JInternalFrame frame:frames) {
            JMenuItem item = new JMenuItem(new ToFrontAction(frame));
            if(desk.getSelectedFrame()==frame) {
                item.setIcon(flagIcon);
            }
            add(item);
        }
    }
    private void reAddMenus(JInternalFrame[] frames) {
        for(JMenuItem it:cstMenus) add(it);
        if(frames!=null && frames.length>0) addSeparator();
    }
    public static void cascade( JDesktopPane desktopPane, int layer ) {
        JInternalFrame[] frames = desktopPane.getAllFramesInLayer( layer );
        if ( frames.length == 0) return;
     
        cascade( frames, desktopPane.getBounds(), 24 );
    }
    public static void cascade( JDesktopPane desktopPane ) {
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if ( frames.length == 0) return;
     
        cascade( frames, desktopPane.getBounds(), 24 );
    }
    private static void cascade( JInternalFrame[] frames, Rectangle dBounds, int separation ) {
        int margin = frames.length*separation + separation;
        int width = dBounds.width - margin;
        int height = dBounds.height - margin;
        for ( int i = frames.length-1; i >=0 ; i--) {
            frames[i].setBounds( dBounds.x + (frames.length-i-1)*separation,
                                 dBounds.y + (frames.length-i-1)*separation,
                                 width, height );
            try {
                frames[i].setIcon(false);
            } catch(Throwable t) {}
            frames[i].toFront();
            if(i==0) {
                frames[i].getDesktopPane().getDesktopManager().activateFrame(frames[i]);
                try {
                    frames[i].setSelected(true);
                } catch(Throwable t) {}
            }
        }
    }
    public static void tile( JDesktopPane desktopPane, int layer ) {
        JInternalFrame[] frames = desktopPane.getAllFramesInLayer( layer );
        if ( frames.length == 0) return;
     
        tile( frames, desktopPane.getBounds() );
    }
    public static void tile( JDesktopPane desktopPane ) {
        JInternalFrame[] frames = desktopPane.getAllFrames();
        if ( frames.length == 0) return;
     
        tile( frames, desktopPane.getBounds() );
    }
    private static void tile( JInternalFrame[] frames, Rectangle dBounds ) {
        int cols = (int)Math.sqrt(frames.length);
        int rows = (int)(Math.ceil( ((double)frames.length) / cols));
        int lastRow = frames.length - cols*(rows-1);
        int width, height;
     
        if ( lastRow == 0 ) {
            rows--;
            height = dBounds.height / rows;
        }
        else {
            height = dBounds.height / rows;
            if ( lastRow < cols ) {
                rows--;
                width = dBounds.width / lastRow;
                for (int i = 0; i < lastRow; i++ ) {
                    frames[cols*rows+i].setBounds( i*width, rows*height,width, height );
                    try {
                        frames[cols*rows+i].setIcon(false);
                    } catch(Throwable t) {}
                }
            }
        }
                
        width = dBounds.width/cols;
        for (int j = 0; j < rows; j++ ) {
            for (int i = 0; i < cols; i++ ) {
                frames[i+j*cols].setBounds( i*width, j*height,width, height );
                try {
                    frames[i+j*cols].setIcon(false);
                } catch(Throwable t) {}
            }
        }
    }

    public class ToFrontAction extends AbstractAction {
        /**
         * Comment for <code>serialVersionUID</code>
         */
        private static final long serialVersionUID = 1L;
        private JInternalFrame frame = null;
        public ToFrontAction(JInternalFrame frame) {
            super(frame.getTitle());
            this.frame = frame;
        }
        public void actionPerformed(ActionEvent evt) {
            if(!frame.isSelected()) {
                frame.getDesktopPane().getDesktopManager().activateFrame(frame);
                try {
                    frame.setIcon(false);
                    frame.setSelected(true);
                } catch(Throwable t) {}
            } else {
                if(frame.isIcon()) {
                    frame.getDesktopPane().getDesktopManager().activateFrame(frame);
                    try {
                        frame.setIcon(false);
                        frame.setSelected(true);
                    } catch(Throwable t) {}
                } else {
                    try {
                        frame.setIcon(true);
                    } catch(Throwable t) {}
                }
            }
        }
    }
}
