/*
Tiamat - a role-playing game framework
ConfigurationEditorFrame.java - used to edit a configuration file
 
 Copyright  (C) 2006 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.Dimension;
import java.util.Enumeration;
import java.util.Properties;

import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.AbstractTableModel;

import com.huguesjohnson.fileFilter.XmlFileFilter;
import com.huguesjohnson.serialization.XmlFormatter;
import com.huguesjohnson.tiamat.StringTable;
import com.huguesjohnson.ui.FileBrowsePanel;

//TODO - this is incomplete because it's not yet used a stand-alone editor, this is only available through the Adventure Studio so it has a limited amount of functionality

/** 
 * ConfigurationEditorFrame - used to edit an configuration file
 * @author Hugues Johnson
 */
public class ConfigurationEditorFrame extends BaseEditorFrame{
	private class ConfigTableModel extends AbstractTableModel{
		/* 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=6550174494257047302L;

		public ConfigTableModel(StringTable table){
			//copy the table to a new instance (to support being able to cancel out changes because of pointers 'n stuff)
			this.updatedTable=new StringTable();
			Properties properties=table.getProperties();
			int size=properties.size();
			this.data=new String[2][];
			this.data[0]=new String[size];
			this.data[1]=new String[size];
			Enumeration keys=properties.propertyNames();
			int counter=0;
			while(keys.hasMoreElements()){
				String key=(String)keys.nextElement();
				String value=properties.getProperty(key);
				this.updatedTable.set(key,value);
				this.data[0][counter]=key;
				this.data[1][counter]=value;
				counter++;
			}
		}
		
	    private String[] columnNames={"Key","Value"};
	    private String[][] data; //the data 
	    private StringTable updatedTable;
	    
	    public int getColumnCount(){ return(this.columnNames.length); }
	    public int getRowCount(){ return(this.updatedTable.getProperties().size()); }
	    public String getColumnName(int col){ return(this.columnNames[col]); }
	    public Object getValueAt(int row,int col){ return(this.data[col][row]); }
	    public boolean isCellEditable(int row,int col){
	    	if(col==1){ 
	    		return(true);
	    	}
	    	return(false);
	    }
	    public void setValueAt(Object value,int row,int col){
	        if(value instanceof String){
		    	this.data[col][row]=(String)value;
		    	this.updatedTable.set(this.data[0][row],(String)value);
		        this.fireTableCellUpdated(row,col);
	        }
	    }
	    public StringTable getUpdatedStringTable(){ return(this.updatedTable); }
	}
	
	/* 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=-8134317800840900334L;

	private FileBrowsePanel browsePanel;
	private JTable configTable;
	
	public ConfigurationEditorFrame(){
		super("Configuration");
	}
	
	public ConfigurationEditorFrame(String editorName){
		super(editorName);
		// TODO Auto-generated constructor stub
	}

	public ConfigurationEditorFrame(String editorName,String filePath){
		super(editorName);
		this.openConfigurationFile(filePath);
	}

	@Override
	protected void initComponents(){
		this.panelContent.setLayout(new BoxLayout(this.panelContent,BoxLayout.Y_AXIS));
		//add the browse panel
		FileFilter[] filters=new FileFilter[1];
		filters[0]=new XmlFileFilter();
		this.browsePanel=new FileBrowsePanel("Configuration File",filters,false);
		this.panelContent.add(this.browsePanel);
		//add table or something
		JPanel tablePanel=new JPanel();
		tablePanel.setLayout(new BoxLayout(tablePanel,BoxLayout.Y_AXIS));
		this.configTable=new JTable();
		JScrollPane scrollPane=new JScrollPane(this.configTable);
		scrollPane.setMinimumSize(new Dimension(200,300));
		scrollPane.setPreferredSize(new Dimension(200,300));
		this.panelContent.add(scrollPane);
		//pack so everything should be visible
		this.pack();
		//disable save by default
		this.disableSave();
	}	
	
	private boolean openConfigurationFile(String filePath){
		boolean success=true;
		String currentFilePath=new String(this.browsePanel.getFilePath());
		try{
			XmlFormatter formatter=new XmlFormatter();
			StringTable table=(StringTable)formatter.loadFrom(filePath);
			this.configTable.setModel(new ConfigTableModel(table));
			this.enableSave();
			//update the browse panel if needed
			if(!currentFilePath.equals(filePath)){
				this.browsePanel.setFilePath(filePath);
			}
		} catch(Exception x){
			x.printStackTrace();
			success=false;
		}
		return(success);
	}	
	
	@Override
	public void onSave(){
		try{
			StringTable updatedTable=((ConfigTableModel)(this.configTable.getModel())).getUpdatedStringTable();
			(new XmlFormatter()).saveTo(updatedTable,this.browsePanel.getFilePath());
		} catch(Exception x){
			x.printStackTrace();
		}
	}

	@Override
	public void onViewXml(){
		String filePath="file:///"+this.browsePanel.getFilePath();
		this.viewXml(filePath);
	}
	
//TODO the rest of these overrides are not implemented	
	
	@Override
	protected void onSaveAs(){
		// TODO Auto-generated method stub

	}

	@Override
	protected void onNew(){
		// TODO Auto-generated method stub

	}

	@Override
	protected void onOpen(){
		// TODO Auto-generated method stub

	}

	@Override
	protected void onRecentFile(String filePath){
		// TODO Auto-generated method stub

	}

	//for testing
//	public static void main(String[] args){
//		(new ConfigurationEditorFrame("test","D:\\test.xml")).setVisible(true);
//	}
}