/*
 *  Draco Econometrics
 *  Copyright (C) 2006-2007 Approximatrix, LLC
 *  http://www.approximatrix.com
 *  
 *  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 3 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, see <http://www.gnu.org/licenses/>.
 */

package com.approximatrix.draco.io.ui;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JButton;

import java.awt.Component;
import java.awt.FlowLayout;
import javax.swing.JScrollPane;
import java.io.File;
import java.io.PrintWriter;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;


import com.approximatrix.draco.application.ChildFrame;
import com.approximatrix.draco.datamodel.StatTableModel;


/*
 * Created on Jan 27, 2005
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

/**
 * @author armstrongj
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class ExportData extends ChildFrame {

	private static final String DIALOG_NAME = "Export Data Columns";
	
	/** The string for requesting topical help */
	private static final String HELP_KEY = "exportdata";
	
	private javax.swing.JPanel jContentPane = null;
	private StatTableModel current_model = null;
	
	private ExportTableModel export_model = null;
	
	private JPanel jPanel = null;
	private JButton cancel_export_button = null;
	private JButton export_button = null;
	private JTable export_table = null;
	private JScrollPane jScrollPane = null;
	private JButton select_none_button = null;
	private JButton select_all_button = null;
	
	private JButton hide_button = null;
	/**
	 * This is the default constructor
	 */
	public ExportData(StatTableModel information, boolean export_all) {
		super(DIALOG_NAME, 
				true, //resizable
				true, //closable
				true, //maximizable
				true);
		
		current_model = information;
		initialize();
		
		//if(!export_all) {
			//this.setVisible(true);
		//} else {
			this.setVisible(false);
			// Run the export with all column names
		//}
		// Set up the table
		String[] data = new String[current_model.getColumnCount()];
		boolean[] true_or_false = new boolean[current_model.getColumnCount()];
		for(int i=0;i<current_model.getColumnCount();i++) {
			data[i] = current_model.getColumnName(i);
			true_or_false[i] = true;
		}
		
		export_model = new ExportTableModel(data,true_or_false);
		export_table.setModel(export_model);
		
		if(export_all) {
			perform_export();
		}
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
		this.setTitle(DIALOG_NAME);
		this.setSize(374, 252);
		this.setContentPane(getJContentPane());
		this.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		//this.addWindowListener(new java.awt.event.WindowAdapter() { 
		//	public void windowClosing(java.awt.event.WindowEvent e) {    
		//		if(base_manager != null) {
		//			base_manager.closeWindow(ExportData.this);
		//		}
		//		dispose();
		//	}
		//});
		
	}
	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private javax.swing.JPanel getJContentPane() {
		if(jContentPane == null) {
			jContentPane = new javax.swing.JPanel();
			jContentPane.setLayout(new java.awt.BorderLayout());
			jContentPane.add(getJPanel(), java.awt.BorderLayout.SOUTH);
			jContentPane.add(getJScrollPane(), java.awt.BorderLayout.CENTER);
		}
		return jContentPane;
	}
	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */    
	private JPanel getJPanel() {
		if (jPanel == null) {
			java.awt.FlowLayout flowLayout1 = new FlowLayout();
			jPanel = new JPanel();
			jPanel.setLayout(flowLayout1);
			flowLayout1.setAlignment(java.awt.FlowLayout.RIGHT);
			jPanel.add(getSelect_all_button(), null);
			jPanel.add(getSelect_none_button(), null);
			jPanel.add(getExport_button(), null);
			jPanel.add(getCancel_export_button(), null);
		}
		return jPanel;
	}
	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getCancel_export_button() {
		if (cancel_export_button == null) {
			cancel_export_button = new JButton();
			cancel_export_button.setText("Cancel");
			cancel_export_button.addMouseListener(new java.awt.event.MouseAdapter() { 
				public void mouseClicked(java.awt.event.MouseEvent e) {    
					dispose();
				}
			});
		}
		return cancel_export_button;
	}
	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getExport_button() {
		if (export_button == null) {
			export_button = new JButton();
			export_button.setText("Export");
			export_button.addMouseListener(new java.awt.event.MouseAdapter() { 
				public void mouseClicked(java.awt.event.MouseEvent e) {					
				    perform_export();
				}
			});
		}
		return export_button;
	}
	/**
	 * This method initializes jTable	
	 * 	
	 * @return javax.swing.JTable	
	 */    
	private JTable getExport_table() {
		if (export_table == null) {
			export_table = new JTable();
		}
		return export_table;
	}
	/**
	 * This method initializes jScrollPane	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */    
	private JScrollPane getJScrollPane() {
		if (jScrollPane == null) {
			jScrollPane = new JScrollPane();
			jScrollPane.setViewportView(getExport_table());
		}
		return jScrollPane;
	}
	
	class ExportTableModel extends AbstractTableModel {
		
		Object[][] data;
		String[] columnNames = {"Column","Export"};
		
		public ExportTableModel(String[] strings, boolean[] values) {
			data = new Object[strings.length][2];
			for(int i=0;i<strings.length;i++) {
				data[i][0] = strings[i];
				data[i][1] = new Boolean(values[i]);
			}			
		}
		
		public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
        }

        /*
         * JTable uses this method to determine the default renderer/
         * editor for each cell.  If we didn't implement this method,
         * then the last column would contain text ("true"/"false"),
         * rather than a check box.
         */
        public Class getColumnClass(int c) {
            return getValueAt(0, c).getClass();
        }

        /*
         * Don't need to implement this method unless your table's
         * editable.
         */
        public boolean isCellEditable(int row, int col) {
            //Note that the data/cell address is constant,
            //no matter where the cell appears onscreen.
            if (col < 1) {
                return false;
            } else {
                return true;
            }
        }

        /*
         * Don't need to implement this method unless your table's
         * data can change.
         */
        public void setValueAt(Object value, int row, int col) {
            data[row][col] = value;
            fireTableCellUpdated(row, col);
        }
	}
	
	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getSelect_none_button() {
		if (select_none_button == null) {
			select_none_button = new JButton();
			select_none_button.setText("Select None");
			select_none_button.addMouseListener(new java.awt.event.MouseAdapter() { 
				public void mouseClicked(java.awt.event.MouseEvent e) {    
					for(int i=0;i<export_model.getRowCount();i++) {
						export_model.setValueAt(new Boolean(false),i,1);
					}
				}
			});
		}
		return select_none_button;
	}
	/**
	 * This method initializes jButton	
	 * 	
	 * @return javax.swing.JButton	
	 */    
	private JButton getSelect_all_button() {
		if (select_all_button == null) {
			select_all_button = new JButton();
			select_all_button.setText("Select All");
			select_all_button.addMouseListener(new java.awt.event.MouseAdapter() { 
				public void mouseClicked(java.awt.event.MouseEvent e) {    
					for(int i=0;i<export_model.getRowCount();i++) {
						export_model.setValueAt(new Boolean(true),i,1);
					}
				}
			});
		}
		return select_all_button;
	}
	
	private void generate_export_file(String[] column_names) {
		File output = null;
		
		// First get the filename to export as
		JFileChooser chooser = new JFileChooser();
		chooser.setDialogType(JFileChooser.SAVE_DIALOG);
		chooser.setDialogTitle("Save Data As...");
	    if (chooser.showOpenDialog(chooser) == JFileChooser.APPROVE_OPTION) {
	    	try {
	    		PrintWriter out_stream = new PrintWriter(new FileWriter(chooser.getSelectedFile()));
	    		
	    		// First, print headers
	    		for(int i=0;i<column_names.length-1;i++) {
	    			out_stream.print(column_names[i]+",");
	    		}
	    		out_stream.println(column_names[column_names.length-1]);
	    		
	    		// Next, all values
	    		for(int i=0;i<current_model.getRowCount();i++) {
	    			for(int j=0;j<column_names.length;j++) {
	    				int column = current_model.getColumnNumber(column_names[j]);
	    				
	    				Object val = current_model.getValueAt(i,column);
	    				
	    				if(val != null)
	    					out_stream.print(val.toString());
	    				else
	    					out_stream.print(" ");
	    				
	    				if(j<column_names.length-1) {
	    					out_stream.print(",");	    					
	    				} else {
	    					out_stream.println();
	    				}
	    			}
	    		}
	    		
	    		out_stream.close();
	    		
	    	} catch (IOException e) {
	    		JOptionPane.showMessageDialog(jContentPane,"Error writing to "+chooser.getSelectedFile().toString(),"File Error", JOptionPane.ERROR_MESSAGE);
	    	}	    	
	    }

	}
	
	private void perform_export() {
		int counter = 0;
		for(int i=0;i<export_table.getRowCount();i++) {
			Boolean this_cell = (Boolean)export_table.getValueAt(i,1);
			if(this_cell.booleanValue()) {
				counter++;
			}
		}
		
		if(counter == 0) {
			JOptionPane.showMessageDialog(jContentPane,"No columns were selected.  Cancelling...","Export Warning", JOptionPane.INFORMATION_MESSAGE);
			dispose();
			return;
		}
		
		String[] export_columns = new String[counter];
		counter = 0;
		for(int i=0;i<export_table.getRowCount();i++) {
			Boolean this_cell = (Boolean)export_table.getValueAt(i,1);
			if(this_cell.booleanValue()) {
				export_columns[counter] = export_table.getValueAt(i,0).toString();
				counter++;
			}
		}
		
		generate_export_file(export_columns);
		
		dispose();
	}

	/** This dialog does not have any menu items
	 * 
	 * @return null since there are no menu items
	 * @see com.approximatrix.draco.application.ChildFrame#getMenuItems()
	 */
	public JMenu[] getMenuItems() {
		// TODO Auto-generated method stub
		return null;
	}

	/** This dialog does not have any toolbar items
	 * 
	 * @return null since there are no necessary toolbar buttons
	 * @see com.approximatrix.draco.application.ChildFrame#getToolbarButtons()
	 */
	public Component[] getToolbarButtons() {
		// TODO Auto-generated method stub
		return null;
	}

	/** There is no reason to rename the export window
	 * 
	 * @return false
	 * @see com.approximatrix.draco.application.ChildFrame#isRenameable()
	 */
	@Override
	public boolean isRenameable() {
		return false;
	}
	
	/** Returns the help key for the Export Data window
	 * 
	 * @return the proper help key, defined by HELP_KEY
	 * @see #HELP_KEY
	 * @see com.approximatrix.draco.application.ChildFrame#getHelpKey()
	 */
	public String getHelpKey() {
		return HELP_KEY;
	}
	
 }  //  @jve:decl-index=0:visual-constraint="10,10"
