/*
Tiamat - a role-playing game framework
SpriteImagePanel.java - panel for managing sprite images
 
 Copyright  (C) 2004 Hugues Johnson
 
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; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.huguesjohnson.tiamat.tools;

import java.io.File;
import java.lang.String;
import java.util.ArrayList;
import javax.swing.JFileChooser;

/** SpriteImagePanel.java - panel for managing sprite images
 * most of this code was generated through the NetBeans 3.6 form editor
 * @author  Hugues Johnson
 */
public class SpriteImagePanel extends javax.swing.JPanel{
    
	/** Determines if a de-serialized file is compatible with this class. See <a href="http://java.sun.com/j2se/1.5.0/docs/guide/serialization/spec/class.html">Java Object Serialization Specifications</a>. */
	private static final long serialVersionUID=-3910362028436057127L;
	
	//property for last path
    public static String lastPath;
    
    /** Creates new form SpriteImagePanel */
    public SpriteImagePanel(java.lang.String title){
        initComponents();
        ((javax.swing.border.TitledBorder)this.getBorder()).setTitle(title);
        SpriteImagePanel.lastPath=java.lang.System.getProperty("user.dir");
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {//GEN-BEGIN:initComponents
    	this.panelMain = new javax.swing.JPanel();
    	this.scrollPaneSprites = new javax.swing.JScrollPane();
    	this.toolbarSprites = new javax.swing.JToolBar();
    	this.panelButton = new javax.swing.JPanel();
    	this.buttonAdd = new javax.swing.JButton();
    	this.buttonRemove = new javax.swing.JButton();

    	this.setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.Y_AXIS));

    	this.setBorder(new javax.swing.border.TitledBorder("SpriteImagePanel"));
    	this.setMinimumSize(new java.awt.Dimension(350, 180));
    	this.setPreferredSize(new java.awt.Dimension(350, 180));
    	this.panelMain.setLayout(null);

    	this.panelMain.setMinimumSize(new java.awt.Dimension(280, 180));
    	this.scrollPaneSprites.setMinimumSize(new java.awt.Dimension(150, 100));
    	this.scrollPaneSprites.setPreferredSize(new java.awt.Dimension(150, 100));
    	this.toolbarSprites.setFloatable(false);
    	this.scrollPaneSprites.setViewportView(this.toolbarSprites);

    	this.panelMain.add(this.scrollPaneSprites);
    	this.scrollPaneSprites.setBounds(4, 0, 330, 110);

    	this.add(this.panelMain);

    	this.panelButton.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT));

    	this.panelButton.setMaximumSize(new java.awt.Dimension(32767, 100));
    	this.buttonAdd.setMnemonic('A');
    	this.buttonAdd.setText("Add");
    	this.buttonAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonAddActionPerformed(evt);
            }
        });

    	this.panelButton.add(this.buttonAdd);

    	this.buttonRemove.setMnemonic('R');
    	this.buttonRemove.setText("Remove");
    	this.buttonRemove.setToolTipText("Remove all selected images");
    	this.buttonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRemoveActionPerformed(evt);
            }
        });

    	this.panelButton.add(this.buttonRemove);

    	this.add(this.panelButton);

    }//GEN-END:initComponents

    public void buttonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRemoveActionPerformed
        this.removeSelectedImages();
    }//GEN-LAST:event_buttonRemoveActionPerformed

    public void buttonAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonAddActionPerformed
        this.addImage();
    }//GEN-LAST:event_buttonAddActionPerformed
    
    public void addImage(String imagePath){
        try{
            //buffer the image
            java.awt.image.BufferedImage image=javax.imageio.ImageIO.read(new java.io.File(imagePath));
            //create a new button
            javax.swing.JToggleButton newButton=new javax.swing.JToggleButton();
            //set the tooltip to be the path of the selected file
            newButton.setToolTipText(imagePath);
            //paint the icon with the selected image
            newButton.setIcon(new javax.swing.ImageIcon(image));
            //add the new button
            this.toolbarSprites.add(newButton);
            //set last path
            int indexOf=imagePath.lastIndexOf(File.separator);
            if(indexOf>0){
                SpriteImagePanel.lastPath=imagePath.substring(0,indexOf);
            }
            //repaint
            this.validate();
            this.repaint();
        } catch(java.lang.Exception x){
            javax.swing.JOptionPane.showMessageDialog(this.getParent(),x.getMessage(),"Error",javax.swing.JOptionPane.ERROR_MESSAGE);
        }    
    }
    
    /** open a JFileChooser and browse for an image to add */
    private void addImage(){
        javax.swing.JFileChooser fileChooser=new javax.swing.JFileChooser();
        fileChooser.setCurrentDirectory(new java.io.File(SpriteImagePanel.lastPath));
        fileChooser.setMultiSelectionEnabled(false);
        fileChooser.setAcceptAllFileFilterUsed(false);
        fileChooser.setFileFilter(new com.huguesjohnson.fileFilter.ImageFileFilter());
        int returnValue=fileChooser.showOpenDialog(this.getParent());
        if(returnValue==JFileChooser.APPROVE_OPTION){
            java.io.File selectedFile=fileChooser.getSelectedFile();
            java.lang.String parent=selectedFile.getParent();
            this.addImage(selectedFile.getPath());
            if(parent!=null){
                SpriteImagePanel.lastPath=parent;
            }
        }
    }
    
    /** remove the currently selected image */
    private void removeSelectedImages(){
        int count=this.toolbarSprites.getComponentCount();
        int index=0;
        while(index<count){
            if(this.toolbarSprites.getComponentAtIndex(index) instanceof javax.swing.JToggleButton){
                if(((javax.swing.JToggleButton)this.toolbarSprites.getComponent(index)).isSelected()){
                    this.toolbarSprites.remove(index);
                    count--;
                } else{
                    index++;
                }
            } else{
                index++;
            }
        }        
        //repaint
        this.validate();
        this.repaint();
    }

    /** remove all images */
    public void removeAllImages(){
        int count=this.toolbarSprites.getComponentCount();
        int index=0;
        while(index<count){
            if(this.toolbarSprites.getComponentAtIndex(index) instanceof javax.swing.JToggleButton){
                this.toolbarSprites.remove(index);
                count--;
            } else{
                index++;
            }
        }
        //repaint
        this.validate();
        this.repaint();
    }
    
    /** return a list of paths for the images
     * @return list of paths for the images 
     */
    public String[] getImagePaths(){
        ArrayList<String> imagePaths=new ArrayList<String>();
        int count=this.toolbarSprites.getComponentCount();
        for(int index=0;index<count;index++){
            if(this.toolbarSprites.getComponentAtIndex(index) instanceof javax.swing.JToggleButton){
                String text=new String(((javax.swing.JToggleButton)this.toolbarSprites.getComponentAtIndex(index)).getToolTipText());
                imagePaths.add(text);
            }
        }   
        int size=imagePaths.size();
        if(size>0){
            String[] returnList=new String[size];
            for(int index=0;index<size;index++){
                returnList[index]=imagePaths.get(index);
            }
            return(returnList);
        }
		return(new String[0]);
    }
    
    /** I wish java had #debug so this wouldn't compile in release code..
     * @param args the command line arguments
     */
    public static void main(java.lang.String args[]){
        javax.swing.JFrame frame=new javax.swing.JFrame();
        frame.addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                java.lang.System.exit(0);
            }
        });
        frame.getContentPane().add(new SpriteImagePanel("Test"));
        frame.setSize(360,200);
        frame.setVisible(true);
    }    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonAdd;
    private javax.swing.JButton buttonRemove;
    private javax.swing.JPanel panelButton;
    private javax.swing.JPanel panelMain;
    private javax.swing.JScrollPane scrollPaneSprites;
    private javax.swing.JToolBar toolbarSprites;
    // End of variables declaration//GEN-END:variables

}