/*
 * Collections.java, 6 juin 2006
 * 
 * This file is part of FilmZ.
 *
 * Copyright © 2006 Johan Cwiklinski
 *
 * File :               Collections.java
 * Author's email :     johan@x-tnd.be
 * Author's Website :   http://www.x-tnd.be/
 * 
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 * 
 */

/**
 * 
 */
package be.xtnd.films.gui;

import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyVetoException;
import java.sql.SQLException;
import java.text.MessageFormat;

import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.TableColumnModel;

import com.jeta.forms.components.panel.FormPanel;

import be.xtnd.commons.GuiCommons;
import be.xtnd.commons.MessagesCommons;
import be.xtnd.commons.db.Database;
import be.xtnd.commons.db.ResultSetTableModel;
import be.xtnd.commons.db.ResultSetTableModelFactory;
import be.xtnd.commons.gui.EscapeInternalFrame;
import be.xtnd.commons.gui.MainGui;
import be.xtnd.commons.gui.TableSorter;
import be.xtnd.films.Collection;
import be.xtnd.gui.FilmzMain;
import be.xtnd.gui.Menus;

/**
 * @author Johan Cwiklinski
 * @version 0.1 
 * */
public class Collections {
	private Collection collection;
	private GuiCommons commons = new GuiCommons(Messages.getBundle());
	private Liste list;
	private JTable table;
	private ResultSetTableModelFactory factory; 
	/** Nom de la fenêtre liste */
	public static final String LIST_NAME = "liste_colections";
	/** Nom de la fenêtre ajout */
	public static final String NEW_NAME = "nouvelle_collection";
	/** Nom de la fenêtre modification */
	public static final String MODIF_NAME = "modification_collection_";
	private char mode;

	/**
	 * 
	 *
	 */
	public Collections(){}
	
	/**
	 * 
	 *
	 */
	public void getList(){
		list = new Liste();
	}
	
	/**
	 * Construit la requête de recherche 
	 * @return requête
	 */
	public String constructQuery(){
		StringBuffer sb = new StringBuffer(Collection.LIST_QUERY);
		if(!FilmzMain.isParentalActive()) sb.append(" WHERE prive=false");
		/*if(!textfield.getText().trim().equals("")){
			sb.append(" WHERE "+Acteur.VALUE+" LIKE '%"+textfield.getText()+"%'");
		}*/
		String qry = new String();
		qry = sb.toString();
		return qry;
	}

	/** Affiche la fenêtre de création d'un objet */
	public void nouveau(){
		mode = Database.NEW;
		collection = new Collection();
		new DetailWindow();
	}
	
	/**
	 * Affiche la fenêtre de modification d'un objet
	 * @param id identifiant de l'objet à modifier
	 */
	public void modifier(Integer id){
		mode = Database.MODIF;
		collection = new Collection(id);
		new DetailWindow();
	}

	
	private class Liste extends EscapeInternalFrame{
		private static final long serialVersionUID = 5145509424360152871L;

		private Integer id_selected;
		private JPopupMenu popup;

		/**
		 * Construit la liste
		 */
		public Liste(){
			this(new ResultSetTableModelFactory(FilmzMain.db), null);
		}
		
		/**
		 * Construit la liste
		 * @param position position de la fenêtre
		 */
		public Liste(Point position){
			this(new ResultSetTableModelFactory(FilmzMain.db), position);
		}
		
		/**
		 * Construit la liste
		 * @param f factory resultset
		 * @param position position de la fenêtre
		 */
		public Liste(ResultSetTableModelFactory f, Point position) {
			setFrameIcon(Menus.COLLECTIONS_IMAGE);

			FormPanel pane = new FormPanel( "be/xtnd/gui/descriptions/collections_list.jfrm" );
			getContentPane().add(pane);
			
			factory = f;
			table = pane.getTable("liste");
			table.getTableHeader().setReorderingAllowed(false);
			table.addMouseListener(new MouseAdapter(){
				public void mousePressed(MouseEvent e){
			  	  	int nModifier = e.getModifiers();
			    	if ((nModifier & InputEvent.BUTTON3_MASK) != 0) {
						id_selected = new Integer(table.getValueAt(table.rowAtPoint(e.getPoint()),0).toString());
						table.changeSelection(table.rowAtPoint(e.getPoint()),0,false,false);
						popup.show((Component)e.getSource(),e.getX(),e.getY());
			      	}
			    	if(InputEvent.BUTTON1_MASK !=0){
			    		if(e.getClickCount()==2){
							id_selected = new Integer(table.getValueAt(table.rowAtPoint(e.getPoint()),0).toString());
							if(MainGui.verifUnicite(MODIF_NAME+id_selected,null)){
								modifier(id_selected);
							}
							/*if(fromJoin){
								ajout(id_selected);
								af.displayQueryResults();
							}else{
								objet[2] = table.getValueAt(table.rowAtPoint(e.getPoint()),1).toString();
							}*/
							//dispose();
			    		}
			    	}
				}
			});
			displayQueryResults(constructQuery());
			
			popup = new JPopupMenu();
			popupEntries(popup, Messages.getString("window.table_popup.new"),"new",Menus.NEW_IMAGE);
			popupEntries(popup, Messages.getString("window.table_popup.modif"),"detailled",Menus.FILMZ_ICON);
			popup.addSeparator();
			popupEntries(popup, Messages.getString("window.table_popup.del"),"del",Menus.DELETE_IMAGE);

			table.add(popup);
			
			setIconifiable(false);
			setClosable(true);
			setResizable(true);
			setMaximizable(true);
			setName(LIST_NAME);
			setSize(400, 300);
			if(position==null) position = MainGui.centerOnDesktop(getSize());
			setLocation(position);
			setVisible(true);
			MainGui.desktop.add(this);
			try {setSelected(true);} catch (PropertyVetoException e) {}
		}

		/**
		 * 
		 * @param q
		 */
		public void displayQueryResults(final String q) {
			MainGui.statusBar.setText("Contacting database...");

			EventQueue.invokeLater(new Runnable() {
				public void run() {
					try {
						ResultSetTableModel mod = factory.getResultSetTableModel(q);
						table.setModel(mod);
						
				        TableSorter sorter = new TableSorter(table.getModel());
				        table.setModel(sorter);
				        sorter.setTableHeader(table.getTableHeader());
				        table.getTableHeader().setToolTipText(MessagesCommons.getString("window.messages.tri"));
						
				        TableColumnModel columnModel = table.getColumnModel();
						columnModel.getColumn(0).setPreferredWidth(0);
						columnModel.getColumn(0).setMinWidth(0);
						columnModel.getColumn(0).setMaxWidth(0);
						columnModel.getColumn(3).setPreferredWidth(30);
						columnModel.getColumn(3).setMaxWidth(30);
						columnModel.getColumn(3).setMinWidth(30);

						/*if(!toSelect.equals(""))
							table.changeSelection(
									mod.findString(toSelect, 1)-1,
									1,false,false);*/

						setTitle(Messages.getString("window.collections.titles.list")+" ("+table.getRowCount()+")");
						
						MainGui.statusBar.setText("");
						MainGui.verifUnicite(LIST_NAME,null);
					} catch (SQLException ex) {
						MainGui.statusBar.setText("Error contacting database !");
						JOptionPane.showMessageDialog(Liste.this,
								new String[] { // Display a 2-line message
								ex.getClass().getName() + ": ", ex.getMessage() });
						MainGui.statusBar.setText("");					
					}
				}
			});
		}	
	
		@Override
		protected void popupActions(ActionEvent event){
			String command = event.getActionCommand();
			if(command.equals("new")){
				if(MainGui.verifUnicite(NEW_NAME,null)){
					nouveau();
				}
			}else if(command.equals("del")){
				/*supprimer(id_selected);
				try {
					displayQueryResults(constructQuery());
				} catch (Exception e1) {e1.printStackTrace();}*/
			}else if(command.equals("detailled")){
				if(MainGui.verifUnicite(MODIF_NAME+id_selected,null)){
					modifier(id_selected);
				}
			}
		}	

	}

	private class DetailWindow extends EscapeInternalFrame{
		private static final long serialVersionUID = 3225615238459711945L;
		private JTextField nom, table;
		private JLabel nom_label, table_label;
		private JCheckBox prive;
		
		DetailWindow(){
			super();
			super.setFrameIcon(Menus.COLLECTIONS_IMAGE);
			if(mode==Database.NEW){
				super.setTitle(Messages.getString("window.collections.titles.new"));
				super.setName(NEW_NAME);				
			}else{
				Object[] args = {collection.getNom()};
				String titre = MessageFormat.format(Messages.getString("window.collections.titles.modif"), args);
				super.setTitle(titre);
				super.setName(MODIF_NAME+collection.getId());				
			}
			fenetreChamps();
		}
					
		void fenetreChamps(){
			FormPanel pane = new FormPanel( "be/xtnd/gui/descriptions/collections.jfrm" );
			
			initLabels(pane);
			
			nom = pane.getTextField("nom");
			nom.setText(collection.getNom());
			
			table = pane.getTextField("table");
			table.setText(collection.getTable());
			if(mode == Database.MODIF){
				table.setEnabled(false);
				table_label.setEnabled(false);
			}
			
			prive = pane.getCheckBox("prive");
			prive.setText(Messages.getString("window.collections.labels.prive"));
			prive.setToolTipText(Messages.getString("window.collections.labels.prive.tooltip"));
			prive.setSelected(collection.isPrive());
									
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			setClosable(true);
			setIconifiable(true);
			
			add(pane);
			
			commons.createButtonBar(this,new OkayEvent());
			
			pack();
			setVisible(true);
			setLocation(MainGui.centerOnDesktop(getSize()));
			MainGui.desktop.add(this,JLayeredPane.MODAL_LAYER);
			try {setSelected(true);} catch (PropertyVetoException e) {}			
		}
		
		private void queries(){
			boolean nouveau = false;
			String titre = new String();
			int boite = 0;
			String message = new String();
			
			collection.setNom(nom.getText());
			collection.setTable(table.getText());
			collection.setPrive(prive.isSelected());
						
			if(mode==Database.NEW){
				titre = Messages.getString("window.collections.messages.added.title");
				nouveau = true;
			}else{
				titre = Messages.getString("window.collections.messages.modified.title");
				nouveau = false;
			}
			collection.enregistrer(nouveau);

			Object[] args = {collection.getNom()};
			if(collection.getAffectedRows()>0){
				boite = JOptionPane.INFORMATION_MESSAGE+JOptionPane.OK_OPTION;
				if(mode==Database.NEW){
					message = MessageFormat.format(Messages.getString("window.collections.messages.added"), args);
				}else if(mode==Database.MODIF){
					message = MessageFormat.format(Messages.getString("window.collections.messages.modified"), args);
				}
				dispose();
				try {
					if(!MainGui.verifUnicite(LIST_NAME, null)){
						list.displayQueryResults(constructQuery());
					}
				} catch (Exception e1) {e1.printStackTrace();}
				//if(select)
				//toSelect = object.getValeur();
			}else{
				boite = JOptionPane.WARNING_MESSAGE+JOptionPane.OK_OPTION;
				if(collection.getSqlMessage().equals("")) collection.setSqlMessage(MessagesCommons.getString("window.messages.noerror"));
				if(mode==Database.NEW){
					message = MessageFormat.format(Messages.getString("window.collections.messages.notadded"), args);
				}else if(mode==Database.MODIF){
					message = MessageFormat.format(Messages.getString("window.collections.messages.notmodified"), args);
				}
				message = message + "\n("+collection.getSqlMessage()+")";
			}
			JOptionPane.showMessageDialog(MainGui.desktop, message, titre, boite);
		}	
		
		private void initLabels(FormPanel pane){
			nom_label = pane.getLabel("nom_label");
			nom_label.setText(Messages.getString("window.collections.labels.nom"));

			table_label = pane.getLabel("table_label");
			table_label.setText(Messages.getString("window.collections.labels.table"));
		}
		
		private boolean verifEntrees(){
			boolean valid = true;
			StringBuffer sb = new StringBuffer();
			sb.append(MessagesCommons.getString("window.messages.required"));

			if(nom.getText().trim().equals("")){
				sb.append(Messages.getString("window.collections.required.nom"));
				if(valid) nom.requestFocus();
				valid = false;
			}
			if(table.getText().trim().equals("")){
				sb.append(Messages.getString("window.collections.required.table"));
				if(valid) table.requestFocus();
				valid = false;
			}
			if(!valid){
				JOptionPane.showMessageDialog(
					MainGui.desktop, 
					sb.toString(),
					MessagesCommons.getString("window.messages.error"),
					JOptionPane.ERROR_MESSAGE);			
			}
			return valid;
		}
		
		class OkayEvent implements ActionListener{
			/**
			 * @param e
			 */
			public void actionPerformed(ActionEvent e) {
				if(verifEntrees())
					queries();
			}		
		}
	}

}
