/*
Tiamat - a role-playing game framework
AreaEditorFrame.java - main window for editing an Area
 
 Copyright  (C) 2004-2005 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.awt.BorderLayout;
import java.io.File;
import javax.swing.BoxLayout;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;
import com.huguesjohnson.PathResolver;
import com.huguesjohnson.fileFilter.XmlFileFilter;
import com.huguesjohnson.serialization.XmlFormatter;
import com.huguesjohnson.tiamat.Area;
import com.huguesjohnson.tiamat.graphics.Layer;
import com.huguesjohnson.ui.FileBrowsePanel;

/** AreaEditorFrame - main window for editing an Area
 * @author Hugues Johnson
 */
public class AreaEditorFrame extends BaseEditorFrame{
    private JPanel panelAreaFile;
    private JPanel panelCharacterList;
    private JPanel panelCharacterListLayerList;
    private JPanel panelLayerList;
    private FileBrowsePanel browsePanel;
    private CharacterListPanel characterListPanel;
    private LayerListPanel layerListPanel;
    
	/** 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=8022750946051963526L;
	
	/** Creates new form AreaEditorFrame 
     */
    public AreaEditorFrame(){
    	super("Area");
    }

    /** Creates new form AreaEditorFrame 
     * @param areaFilePath the file to load
     */
    public AreaEditorFrame(String areaFilePath){
    	super("Area");
        this.loadArea(areaFilePath);
    }
         
    protected void initComponents(){
        this.panelContent.setLayout(new BoxLayout(this.panelContent,BoxLayout.Y_AXIS));
        
        this.panelAreaFile=new JPanel();
    	this.panelAreaFile.setLayout(new BorderLayout());
        this.panelContent.add(this.panelAreaFile);

    	this.panelCharacterListLayerList=new JPanel();
        this.panelCharacterListLayerList.setLayout(new BoxLayout(this.panelCharacterListLayerList,BoxLayout.X_AXIS));
    	
        this.panelCharacterList=new JPanel();
        this.panelCharacterListLayerList.add(this.panelCharacterList);

        this.panelLayerList=new JPanel();
        this.panelCharacterListLayerList.add(this.panelLayerList);
        this.panelContent.add(this.panelCharacterListLayerList);

        FileFilter[] filters=new FileFilter[1];
        filters[0]=new XmlFileFilter();
        this.browsePanel=new FileBrowsePanel("Area File",filters,false);
        this.panelAreaFile.add(this.browsePanel);
        this.characterListPanel=new com.huguesjohnson.tiamat.tools.CharacterListPanel();
        this.panelCharacterList.add(this.characterListPanel);
        this.layerListPanel=new com.huguesjohnson.tiamat.tools.LayerListPanel();
        this.panelLayerList.add(this.layerListPanel);

        //pack so everything's visible
        this.pack();
        
        //disable save by default
        this.disableSave();
    }

    protected void onViewXml(){
        String filePath="file:///"+this.browsePanel.getFilePath();
        this.viewXml(filePath);
    }

    protected void onNew(){
        this.browsePanel.clear();
        this.newArea();
    }
    
    /** create a new area 
     */
    private void newArea(){
        this.characterListPanel.clear();
        this.layerListPanel.clear();
        this.disableSave();
    }
    
    protected void onOpen(){
        boolean success=true;
        String currentFilePath=new String(this.browsePanel.getFilePath());
        if(this.browsePanel.browse()){    
            String newFilePath=new String(this.browsePanel.getFilePath());
            success=this.loadArea(newFilePath);
            //if the open operation failed set the file path back to the old one
            if(!success){
                this.browsePanel.setFilePath(currentFilePath);
            }
        }
        if(success){
            this.enableSave();
            this.addRecentFile(this.browsePanel.getFilePath());
        }
    }

    protected void onRecentFile(String filePath){
        boolean success=true;
        this.browsePanel.setFilePath(filePath);
        String currentFilePath=new String(this.browsePanel.getFilePath());
        success=this.loadArea(filePath);
        //if the open operation failed set the file path back to the old one
        if(!success){
        	this.browsePanel.setFilePath(currentFilePath);
        } else{
            this.enableSave();
        }
    }
    
    /** load a saved area from a file 
     * @return success
     */
    private boolean loadArea(String filePath){
        boolean success=true;
        try{
            XmlFormatter formatter=new XmlFormatter();
            Area area=(Area)formatter.loadFrom(filePath);
            String currentDir=filePath.substring(0,filePath.lastIndexOf(File.separator)+1);
            //clear the existing stuff
            this.newArea();
            //set the file path
            this.browsePanel.setFilePath(filePath);
            //add characters
            String[] characterPaths=area.getCharacterPaths();
            if(characterPaths!=null){
                int length=characterPaths.length;
                for(int index=0;index<length;index++){
                    this.characterListPanel.addCharacter(PathResolver.getAbsolutePath(currentDir,characterPaths[index]));
                }
            }
            //layers
            Layer layers[]=area.getLayers();
            if(layers!=null){
                int length=layers.length;
                for(int index=0;index<length;index++){
                    this.layerListPanel.addLayer(layers[index]);
                }
            }
        } catch(Exception x){
            success=false;
            x.printStackTrace();
            JOptionPane.showMessageDialog(this,"Error loading Area: "+x.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
        }
        return(success);
    }

    protected void onSaveAs(){
        if(this.browsePanel.browse()){
            String filePath=this.browsePanel.getFilePath();
        	if(!filePath.toLowerCase().endsWith(".area.xml")){
        		this.browsePanel.setFilePath(filePath+".area.xml");
        	}
        	this.onSave();
            this.enableSave();
            this.addRecentFile(this.browsePanel.getFilePath());
        }
    }    
    
    protected void onSave(){
        String filePath=this.browsePanel.getFilePath();
        String currentDir=this.browsePanel.getDirectory();
        XmlFormatter formatter=new XmlFormatter();
        if(filePath!=null){
            if(filePath.length()>0){
                Area area=new Area();
                //get the path to the absolute dir
                area.setAbsoluteDir(this.browsePanel.getDirectory());
                //copy over characters
                String[] characterPaths=this.characterListPanel.getAllCharacterPaths();
                if(characterPaths!=null){
                    int length=characterPaths.length;
                    for(int index=0;index<length;index++){
                        area.addCharacter(PathResolver.getRelativePath(currentDir,characterPaths[index]),formatter);
                    }
                }
                //copy over layers
                Layer[] layers=this.layerListPanel.getAllLayers();
                if(layers!=null){
                    int length=layers.length;
                    for(int index=0;index<length;index++){
                        area.addLayer(layers[index]);
                    }
                }
                //try saving
                try{
                    formatter.saveTo(area,filePath);
                } catch(Exception x){
                    x.printStackTrace();
                    JOptionPane.showMessageDialog(this,"Error saving Area: "+x.getMessage(),"Error",JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    /** create a new AreaEditorFrame
     * @param args the command line arguments
     */
    public static void main(String args[]){
        (new AreaEditorFrame()).setVisible(true);
    }
}