/*
 * Films.java, 10 sept. 2005
 * 
 * This file is part of FilmZ.
 *
 * Copyright © 2005 Johan Cwiklinski
 *
 * File :               Films.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.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyVetoException;
import java.io.File;
import java.io.FilenameFilter;
import java.sql.SQLException;
import java.text.MessageFormat;
import java.util.List;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;
import javax.swing.table.TableColumnModel;

import be.xtnd.commons.GuiCommons;
import be.xtnd.commons.MessagesCommons;
import be.xtnd.commons.db.Database;
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.Film;
import be.xtnd.films.Genre;
import be.xtnd.films.plugins.RechercheWeb;
import be.xtnd.gui.FilmzMain;
import be.xtnd.gui.Menus;

import com.jeta.forms.components.panel.FormPanel;
import com.jeta.forms.components.separator.TitledSeparator;
import com.toedter.calendar.JYearChooser;
import com.toedter.components.JSpinField;

/**
 * 
 *
 * @author Johan Cwiklinski
 */
public class Films {
	protected Film film;
	protected GuiCommons commons = new GuiCommons(Messages.getBundle());
	/** Nom de la fenêtre liste */
	public static final String LIST_NAME = "liste_films";
	/** Nom de la fenêtre d'ajout */
	public static final String NEW_NAME = "nouveau_film";
	protected char mode;
	private Liste liste;
	protected DetailWindow details;
	
	private JTextField titreSearch;
	private JSpinField numeroSearch;
	private JComboBox genresSearch;
	protected JTable table;
	protected ResultSetTableModelFactory factory; 
	//éléments detailwindow
	protected JTextField titre, sous_titre; 
	protected JYearChooser annee;
	protected JSpinField duree, cd;
	//protected JComboBox realisateurs, origines;
	protected JTextArea resume;
	protected JButton sel_realisateur, sel_genre, sel_origine; 
	private boolean local;

	/**
	 * Affiche la liste
	 */
	public void getList(){
		liste = new Liste();
	}

	/**
	 * Affiche la fenêtre d'ajout de film
	 *
	 */
	public void nouveauFilm(){
		//FIXME récupération spécial
		film = new Film();
		mode = Database.NEW;
		details = new DetailWindow(true);
	}
	
	/**
	 * Affiche la fenêtre de modification du film sélectionné
	 * @param id identifiant du film à modifier
	 */
	public void modifieFilm(Integer id){
		//FIXME récupération spécial
		film = new Film(id);
		mode =Database.MODIF;
		details = new DetailWindow(true);
	}
	
	/**
	 * Supprimer un film
	 * @param id identifiant du film à supprimer
	 */
	public void supprimeFilm(Integer id){
		//FIXME récupération spécial
		film = new Film(id);
		Object[] args = {film.getTitre()};
		int result = 0;
		int response = JOptionPane.showConfirmDialog(
				MainGui.desktop, 
				MessageFormat.format(Messages.getString("window.movies.messages.deleted.confirm"), args),
				Messages.getString("window.movies.messages.deleted.title"),
				JOptionPane.YES_NO_OPTION,
				JOptionPane.WARNING_MESSAGE);

		if (response == JOptionPane.YES_OPTION) {
			result = film.delete(id);		

			String strMessage = new String();
			int typeMessage = 0;
			String titreMessage = new String();
			
			if(result>0){
				strMessage = MessageFormat.format(
						Messages.getString("window.movies.messages.deleted"),
						args);
				titreMessage = Messages.getString("window.movies.messages.deleted.title");
				typeMessage = JOptionPane.INFORMATION_MESSAGE;
			}else{
				strMessage = MessageFormat.format(
						Messages.getString("window.movies.messages.notdeleted"),
						args);
				titreMessage = MessagesCommons.getString("window.messages.error");
				typeMessage = JOptionPane.ERROR_MESSAGE;
			}
			JOptionPane.showMessageDialog(
					MainGui.desktop, 
					strMessage,
					titreMessage,
					typeMessage);							
			try {
				if(!MainGui.verifUnicite(Films.LIST_NAME, null)){
		        	liste.storeSort = liste.sorter.getSortingColumns();
					liste.displayQueryResults(liste.constructQuery());
				}
			} catch (Exception e1) {e1.printStackTrace();}
		}
		
	}
	
	/**
	 * Vérifie les champs obligatoires
	 * @return true si les entrées sont valides, flase sinon
	 */
	protected boolean verifEntrees(){
		boolean valid = true;
		StringBuffer sb = new StringBuffer();
		sb.append(MessagesCommons.getString("window.messages.required"));

		if(titre.getText().trim().equals("")){
			sb.append(Messages.getString("window.movies.required.title"));
			if(valid) titre.requestFocus();
			valid = false;
		}
		if(film.getRealisateurs().size()==0){
			sb.append(Messages.getString("window.movies.required.director"));
			if(valid) sel_realisateur.requestFocus();
			valid = false;			
		}
		/*if(realisateurs.getSelectedIndex()==0){
			sb.append(Messages.getString("window.movies.required.director"));
			if(valid) realisateurs.requestFocus();
			valid = false;
		}*/
		if(film.getGenres().size()==0){
			sb.append(Messages.getString("window.movies.required.type"));
			if(valid) sel_genre.requestFocus();
			valid = false;			
		}
		/*if(origines.getSelectedIndex()==0){
			sb.append(Messages.getString("window.movies.required.origin"));
			if(valid) origines.requestFocus();
			valid = false;
		}*/
		if(film.getOrigines().size()==0){
			sb.append(Messages.getString("window.movies.required.origin"));
			if(valid) sel_origine.requestFocus();
			valid = false;			
		}

		if(!valid){
			JOptionPane.showMessageDialog(
				MainGui.desktop, 
				sb.toString(),
				MessagesCommons.getString("window.messages.error"),
				JOptionPane.ERROR_MESSAGE);			
		}
		return valid;
	}

	/**
	 * Enregistre les données du film
	 *
	 */
	protected void queries(){
		boolean nouveau = false;
		String messageTitre = new String();
		int boite = 0;
		String message = new String();
		
		film.setTitre(titre.getText());
		film.setSous_titre(sous_titre.getText());
		film.setAnnee(new Integer(annee.getValue()));
		//film.setRealisateur(new Realisateur(realisateurs.getSelectedItem().toString()));
		film.setResume(resume.getText());
		film.setDuree(new Integer(duree.getValue()));
		//film.setGenre(new Genre(genres.getSelectedItem().toString(), false));
		film.setCd(new Integer(cd.getValue()));
		//film.setOrigine(new Origine(origines.getSelectedItem().toString()));
		
		if(mode==Database.NEW){
			messageTitre = Messages.getString("window.movies.messages.added.title");
			nouveau = true;
		}else if(mode==Database.MODIF){
			messageTitre = Messages.getString("window.movies.messages.modified.title");
			nouveau = false;
		}
		
		film.enregistrer(nouveau);

		Object[] args = {film.getTitre()};
		if(film.getAffectedRows()>0){
			boite = JOptionPane.INFORMATION_MESSAGE+JOptionPane.OK_OPTION;
			if(mode==Database.NEW){
				message = MessageFormat.format(Messages.getString("window.movies.messages.added"), args);
			}else if(mode==Database.MODIF){
				message = MessageFormat.format(Messages.getString("window.movies.messages.modified"), args);
			}
			details.dispose();
			try {
				if(local && !MainGui.verifUnicite(LIST_NAME, null)){
					String qry = liste.constructQuery();
		        	liste.storeSort = liste.sorter.getSortingColumns();
					liste.displayQueryResults(qry);
				}
			} catch (Exception e1) {e1.printStackTrace();}
		}else{
			boite = JOptionPane.WARNING_MESSAGE+JOptionPane.OK_OPTION;
			if(film.getSqlMessage().equals("")) film.setSqlMessage(MessagesCommons.getString("window.messages.noerror"));
			if(mode==Database.NEW){
				message = MessageFormat.format(Messages.getString("window.movies.messages.notadded"), args);
			}else if(mode==Database.MODIF){
				message = MessageFormat.format(Messages.getString("window.movies.messages.notmodified"), args);
			}
			message = message + "\n("+film.getSqlMessage()+")";
		}
		JOptionPane.showMessageDialog(MainGui.desktop, message, messageTitre, boite);
	}	

	protected class DetailWindow extends EscapeInternalFrame{
		private static final long serialVersionUID = -3516085133189643664L;
		private JButton acteurs, cover, back, forward, web;
		private JLabel titre_label, sous_titre_label, annee_label, realisateur_label, genre_label, duree_label,
		cd_label, resume_label, origine_label, cover_label, detail_cover, genres, realisateurs, origines;
		private int coverCount, currentCover;		
        private File[] children;
        private String directory = FilmzMain.prefs.getCovers_path(); //"covers";
		
		protected DetailWindow(boolean loc){
			super();
			local = loc;
			if(local){
				if(mode==Database.NEW){
					super.setTitle(Messages.getString("window.movies.titles.new"));
					super.setName(NEW_NAME);				
				}else{
					Object[] args = {film.getTitre()};
					String titre = MessageFormat.format(Messages.getString("window.movies.titles.modif"), args);
					super.setTitle(titre);
					super.setName("film_"+film.getId());				
				}
				fenetreChamps();
			}
		}
					
		void fenetreChamps(){
			FormPanel pane = new FormPanel( "be/xtnd/gui/descriptions/film.jfrm" );
			
			initLabels(pane);
			
			titre = pane.getTextField("titre");
			titre.setText(film.getTitre());
			
			web = (JButton)pane.getButton("web_btn");
			web.setToolTipText(Messages.getString("window.movies.buttons.websearch"));
			web.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(titre.getText().trim().equals("")){
	    		    	JOptionPane.showMessageDialog(
	    		    			MainGui.desktop,
								Messages.getString("window.movies.messages.title_required"),
								MessagesCommons.getString("window.messages.error"),
								JOptionPane.ERROR_MESSAGE
	    		    	);				
					}else{
						dispose();
						if(mode==Database.NEW){
							new RechercheWeb(titre.getText());
						}else if(mode==Database.MODIF){
							new RechercheWeb(titre.getText(), film);						
						}
					}
				}
			});
			
			sous_titre = pane.getTextField("sous_titre");
			sous_titre.setText(film.getSous_titre());
			
			annee = (JYearChooser)pane.getComponentByName("annee");
			annee.setStartYear(0);annee.setEndYear(9999);
			annee.setPreferredSize(new Dimension(60,20));
			annee.setHorizontalAlignment(SwingConstants.RIGHT);
			annee.setValue(film.getAnnee().intValue());

			realisateurs = pane.getLabel("realisateur");
			StringBuffer g = new StringBuffer();
			for(int i = 0 ; i < film.getRealisateurs().size() ; i++){
				if(i>0) g.append(", ");
				g.append(film.getRealisateurs().get(i).getRealisateur());
			}
			realisateurs.setText(g.toString());
		
			sel_realisateur = (JButton)pane.getButton("sel_realisateur");
			sel_realisateur.setToolTipText(Messages.getString("window.movies.buttons.directors"));
			sel_realisateur.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(MainGui.verifUnicite(RealisateursFilms.FOR_FILM_NAME+((film.getId()==null)?"new":film.getId()),null)){
						new RealisateursFilms(film, mode, realisateurs);
					}
				}
			});
			
			genres = pane.getLabel("genre");
			g = new StringBuffer();
			for(int i = 0 ; i < film.getGenres().size() ; i++){
				if(i>0) g.append(", ");
				g.append(film.getGenres().get(i).getGenre());
			}
			genres.setText(g.toString());

			sel_genre = (JButton)pane.getButton("sel_genre");
			sel_genre.setToolTipText(Messages.getString("window.movies.buttons.types"));
			sel_genre.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(MainGui.verifUnicite(GenresFilms.FOR_FILM_NAME+((film.getId()==null)?"new":film.getId()),null)){
						new GenresFilms(film, mode, genres);
					}
				}
			});

			duree = (JSpinField)pane.getComponentByName("duree");
			duree.setPreferredSize(new Dimension(60,20));
			duree.setValue(film.getDuree());

			cd = (JSpinField)pane.getComponentByName("cd");
			cd.setPreferredSize(new Dimension(60,20));
			cd.setValue(film.getCd().intValue());
			
			acteurs = (JButton)pane.getButton("acteurs");
			acteurs.setText(Messages.getString("window.movies.buttons.actors"));
			acteurs.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(MainGui.verifUnicite(ActeursFilms.FOR_FILM_NAME+((film.getId()==null)?"new":film.getId()),null)){
						new ActeursFilms(film, mode, null);
					}
				}				
			});
			
			resume = (JTextArea)pane.getComponentByName("resume");
			resume.setText(film.getResume());
			
			origines = pane.getLabel("origine");
			g = new StringBuffer();
			for(int i = 0 ; i < film.getOrigines().size() ; i++){
				if(i>0) g.append(", ");
				g.append(film.getOrigines().get(i).getOrigine());
			}
			origines.setText(g.toString());
			
			sel_origine = (JButton)pane.getButton("sel_origine");
			sel_origine.setToolTipText(Messages.getString("window.movies.buttons.origins"));
			sel_origine.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					if(MainGui.verifUnicite(OriginesFilms.FOR_FILM_NAME+((film.getId()==null)?"new":film.getId()),null)){
						new OriginesFilms(film, mode, origines);
					}
				}
			});

			cover = (JButton)pane.getButton("modifier_jacquette");
			cover.setToolTipText(Messages.getString("window.movies.buttons.cover"));
			
			cover_label = pane.getLabel("jacquette");
			cover_label.setMinimumSize(new Dimension(300,300));
			cover_label.setPreferredSize(new Dimension(300,300));

			if(mode!=Database.NEW){
			    ComponentListener listener = new ComponentAdapter() {	    
			        public void componentResized(ComponentEvent evt) {
			        	if(children.length>0){
			        		coverImage(new ImageIcon(directory+"/"+children[currentCover].getName()));
			        	}
			        }
			    };
			    cover_label.addComponentListener(listener);
	
		        File dir = new File(directory);
		        
		        FilenameFilter filter = new FilenameFilter() {
		            public boolean accept(File dir, String name) {
		                return name.startsWith(film.getId().toString()+"_-");
		            }
		        };
		        children = dir.listFiles(filter);
		        
		        if (children == null) {
		        	Object[] args = {directory};
		    		int response = JOptionPane.showConfirmDialog(
		    				MainGui.desktop, 
		    				MessageFormat.format(MessagesCommons.getString("window.messages.missing_dir"), args),
		    				MessagesCommons.getString("window.messages.error"),
		    				JOptionPane.YES_NO_OPTION,
		    				JOptionPane.WARNING_MESSAGE);
	
		    		if (response == JOptionPane.YES_OPTION) {
		    		    boolean success = (new File(directory)).mkdirs();
		    		    if (!success) {
		    		    	JOptionPane.showMessageDialog(
		    		    			MainGui.desktop,
									MessageFormat.format(MessagesCommons.getString("window.messages.make_dir_failed"),args),
									MessagesCommons.getString("window.messages.error"),
									JOptionPane.ERROR_MESSAGE
		    		    	);
		    		    }
		    		}
		        } else {
		        	if(children.length>0){
		        		coverImage(new ImageIcon(directory+"/"+children[0].getName()));
		        	}
		        }
		        
		        coverCount = children.length;
		        currentCover = 0;
			}
	        back = (JButton)pane.getButton("back");
	        back.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
		        	if(children.length>0){
		        		currentCover--;
		        		if(currentCover<0) currentCover=coverCount-1;
		        		coverImage(new ImageIcon(directory+"/"+children[currentCover].getName()));
		        		detail_cover.setText(currentCover+1+"/"+coverCount);
		        	}
				}
			});
	        if(mode==Database.NEW){
	        	back.setEnabled(false);
	        }else if(children.length==0) back.setEnabled(false);
	        forward = (JButton)pane.getButton("forward");
	        forward.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
		        	if(children.length>0){
		        		currentCover++;
		        		if(currentCover>coverCount-1) currentCover=0;
		        		coverImage(new ImageIcon(directory+"/"+children[currentCover].getName()));
		        		detail_cover.setText(currentCover+1+"/"+coverCount);
		        	}
				}
			});
	        if(mode==Database.NEW){
	        	forward.setEnabled(false);
	        }else if(children.length==0) forward.setEnabled(false);

	        detail_cover = pane.getLabel("detail_cover");
	        if(mode==Database.NEW){
	        	detail_cover.setText("");
	        }else if(children.length==0){
	        	detail_cover.setText("");
	        }else{
	        	detail_cover.setText(currentCover+1+"/"+coverCount);
	        }
	        
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			setClosable(true);
			setMaximizable(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 coverImage(ImageIcon origin){
			Image inImage = origin.getImage();
			int maxDim = (cover_label.getWidth()>300)?cover_label.getWidth():300;
			
			double scale = (double) maxDim / (double) inImage.getHeight(null);
			if (inImage.getWidth(null) > inImage.getHeight(null)){
				scale = (double) maxDim / (double) inImage.getWidth(null);
			}

			if(scale>1) scale=1;
			
			int scaledW = (int) (scale * inImage.getWidth(null));
			int scaledH = (int) (scale * inImage.getHeight(null));

			Image img = inImage.getScaledInstance(scaledW , scaledH, Image.SCALE_SMOOTH);
			cover_label.setIcon(new ImageIcon(img));
		}
		
		private void initLabels(FormPanel pane){
			titre_label = pane.getLabel("titre_label"); 
			titre_label.setText(Messages.getString("window.movies.labels.title"));
			
			sous_titre_label = pane.getLabel("sous_titre_label"); 
			sous_titre_label.setText(Messages.getString("window.movies.labels.sub_title"));
			
			annee_label = pane.getLabel("annee_label");
			annee_label.setText(Messages.getString("window.movies.labels.year"));
			
			realisateur_label = pane.getLabel("realisateur_label");
			realisateur_label.setText(Messages.getString("window.movies.labels.director"));
			
			genre_label = pane.getLabel("genre_label");
			genre_label.setText(Messages.getString("window.movies.labels.type"));
			
			duree_label = pane.getLabel("duree_label");
			duree_label.setText(Messages.getString("window.movies.labels.length"));
			
			cd_label = pane.getLabel("cd_label");
			cd_label.setText(Messages.getString("window.movies.labels.cd"));
			
			resume_label = pane.getLabel("resume_label");
			resume_label.setText(Messages.getString("window.movies.labels.summary"));
			
			origine_label = pane.getLabel("origine_label");
			origine_label.setText(Messages.getString("window.movies.labels.origin"));
		}
				
		class OkayEvent implements ActionListener{
			/**
			 * @param e ActionEvent
			 */
			public void actionPerformed(ActionEvent e) {
				if(verifEntrees())
					queries();
			}		
		}
	}
	
	/**
	 * 
	 */
	public class Liste extends EscapeInternalFrame{
		private static final long serialVersionUID = 5635082151587360418L;
		private Integer id_selected;
		private JPopupMenu popup;
		/* list header */
		private TitledSeparator chercher_label;
		private JButton search, reinit;
		private JToggleButton specials_button;
		private JLabel title_label, numero_label, genre_label;
		//private int count;
		/** Ordre de tri des colonnes */
		public List<Object> storeSort = null;
		/** TableSorter de la JTable */
		public TableSorter sorter; 

		/**
		 * Affiche la liste des films avec les paramètres par défaut.
		 *
		 */
		public Liste(){		
			this(new ResultSetTableModelFactory(FilmzMain.db));

			setLocation(MainGui.centerOnDesktop(getSize()));
			setVisible(true);
			MainGui.desktop.add(this);	
		}
		
		/**
		 * Affiche la liste des films à la position spécifiée
		 * @param position point position de la fenêtre à l'affichage
		 */
		public Liste(Point position){
			this(new ResultSetTableModelFactory(FilmzMain.db));

			if(position==null) position = MainGui.centerOnDesktop(getSize());
			setLocation(position);
			setVisible(true);
			MainGui.desktop.add(this);	
		}
		
		/**
		 * Affiche la liste des films avec le ResultSet associé
		 * @param f ResultSetTableModelFactory à afficher
		 * 
		 * @see ResultSetTableModelFactory
		 */
		public Liste(ResultSetTableModelFactory f) {
			setIconifiable(false);
			setClosable(true);
			setResizable(true);
			setMaximizable(true);
			setName(LIST_NAME);
			setSize(550, 450);

			//FIXME récupération spécial
			film = new Film();
			initWindow();
			/*FormPanel pane = new FormPanel( "be/xtnd/gui/descriptions/films_list.jfrm" );
			getContentPane().add(pane);
			
			chercher_label = (TitledSeparator)pane.getComponentByName("title_label");
			chercher_label.setText(Messages.getString("window.search.title"));

			title_label = pane.getLabel("titre_label");
			title_label.setText(Messages.getString("window.movies.labels.title"));
			
			numero_label = pane.getLabel("numero_label");
			numero_label.setText(Messages.getString("window.movies.labels.number"));
			
			genre_label = pane.getLabel("genre_label");
			genre_label.setText(Messages.getString("window.movies.labels.type"));
			
			titreSearch = pane.getTextField("titre");
			numeroSearch = (JSpinField)pane.getComponentByName("numero");
			numeroSearch.setMinimum(0);
			numeroSearch.setMaximum(film.getMax());
			
			genresSearch = pane.getComboBox("genre");
			commons.buildCombo(genresSearch, new Genre().listing());
			
			search = (JButton)pane.getButton("search_button");
			search.setText(Messages.getString("window.search.button"));
			search.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
			        	storeSort = sorter.getSortingColumns();
						displayQueryResults(constructQuery());
					} catch (Exception e1) {e1.printStackTrace();}
				}
			});
			
			reinit = (JButton)pane.getButton("reinit_button");
			reinit.setText(Messages.getString("window.search.reinit"));
			reinit.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					numeroSearch.setValue(0);
					genresSearch.setSelectedIndex(0);
					titreSearch.setText("");
					storeSort = null;
					displayQueryResults(
							(specials_button.isSelected())?Film.LIST_QUERY_SPECIALS:Film.LIST_QUERY
							);
				}
			});
			
			specials_button = (JToggleButton)pane.getButton("specials_button");
			specials_button.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					displayQueryResults(
							(specials_button.isSelected())?Film.LIST_QUERY_SPECIALS:Film.LIST_QUERY
							);
				}
			});
			specials_button.setVisible(FilmzMain.isParentalActive());

			table = pane.getTable("liste");*/
			factory = f;
	    	this.getRootPane().setDefaultButton(search);
			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 (e.getClickCount() == 2) {// double-click
		            	id_selected = new Integer(table.getValueAt(table.rowAtPoint(e.getPoint()),0).toString());
						if(MainGui.verifUnicite("film_"+id_selected,null)){
							modifieFilm(id_selected);
						}
					}

				}
			});
			displayQueryResults(Film.LIST_QUERY);
			/*displayQueryResults(
					(specials_button.isSelected())?Film.LIST_QUERY_SPECIALS:Film.LIST_QUERY
					);*/
			
			popup = new JPopupMenu();
			JMenu menuTri = new JMenu(Messages.getString("window.table_popup.order"));
			popupEntries(popup, menuTri, Messages.getString("window.table_popup.order.number"),"orderOrdre",null);
			popupEntries(popup, menuTri, Messages.getString("window.table_popup.order.title"),"orderTitle",null);
			popupEntries(popup, menuTri, Messages.getString("window.table_popup.order.type"),"orderGenre",null);
			JMenu menuFiltre = new JMenu(Messages.getString("window.table_popup.filter"));
			popupEntries(popup, menuFiltre, Messages.getString("window.table_popup.order.type"),"filterGenre",null);
			
			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.web"),"web",Menus.SEARCH_IMAGE);
			popup.addSeparator();
			popupEntries(popup, Messages.getString("window.table_popup.del"),"del",Menus.DELETE_IMAGE);

			table.add(popup);
		}
		
		protected void initWindow(){
			FormPanel pane = new FormPanel( "be/xtnd/gui/descriptions/films_list.jfrm" );
			getContentPane().add(pane);
			
			chercher_label = (TitledSeparator)pane.getComponentByName("title_label");
			chercher_label.setText(Messages.getString("window.search.title"));

			title_label = pane.getLabel("titre_label");
			title_label.setText(Messages.getString("window.movies.labels.title"));
			
			numero_label = pane.getLabel("numero_label");
			numero_label.setText(Messages.getString("window.movies.labels.number"));
			
			genre_label = pane.getLabel("genre_label");
			genre_label.setText(Messages.getString("window.movies.labels.type"));
			
			titreSearch = pane.getTextField("titre");
			numeroSearch = (JSpinField)pane.getComponentByName("numero");
			numeroSearch.setMinimum(0);
			numeroSearch.setMaximum(film.getMax());
			
			genresSearch = pane.getComboBox("genre");
			commons.buildCombo(genresSearch, new Genre().listing());
			
			search = (JButton)pane.getButton("search_button");
			search.setText(Messages.getString("window.search.button"));
			search.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try {
			        	storeSort = sorter.getSortingColumns();
						displayQueryResults(constructQuery());
					} catch (Exception e1) {e1.printStackTrace();}
				}
			});
			
			reinit = (JButton)pane.getButton("reinit_button");
			reinit.setText(Messages.getString("window.search.reinit"));
			reinit.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					numeroSearch.setValue(0);
					genresSearch.setSelectedIndex(0);
					titreSearch.setText("");
					storeSort = null;
					displayQueryResults(Film.LIST_QUERY);
					/*displayQueryResults(
							(specials_button.isSelected())?Film.LIST_QUERY_SPECIALS:Film.LIST_QUERY
							);*/
				}
			});
			
			specials_button = (JToggleButton)pane.getButton("specials_button");
			specials_button.addActionListener(new ActionListener(){
				public void actionPerformed(ActionEvent e) {
					displayQueryResults(Film.LIST_QUERY);
					/*displayQueryResults(
							(specials_button.isSelected())?Film.LIST_QUERY_SPECIALS:Film.LIST_QUERY
							);*/
				}
			});
			specials_button.setVisible(FilmzMain.isParentalActive());

			table = pane.getTable("liste");			
		}
		
		/**
		 * Construit la requête de recherche
		 * 
		 * @return chaîne sql de recherche de film
		 * @throws Exception
		 */
		public String constructQuery() throws Exception{
			boolean search = false;
			StringBuffer sb = new StringBuffer(Film.BASE_LIST_QUERY);
			/*StringBuffer sb = new StringBuffer(
					(specials_button.isSelected())?Film.BASE_LIST_QUERY_SPECIALS:Film.BASE_LIST_QUERY
					);*/
			if(!titreSearch.getText().trim().equals("")){
				search=true;
				sb.append(" WHERE (titre LIKE '%"+titreSearch.getText()+"%' OR sous_titre LIKE '%"+titreSearch.getText()+"%')");
			}
			if(numeroSearch.getValue()>0){
				if(search) sb.append(" AND ");
				else sb.append(" WHERE ");
				search=true;
				sb.append(Film.TABLE+"."+Film.PK+"="+numeroSearch.getValue());
				//sb.append((specials_button.isSelected())?Film.TABLE_SPECIALS:Film.TABLE+"."+Film.PK+"="+numeroSearch.getValue());
			}
			if(genresSearch.getSelectedIndex()>0){
				if(search) sb.append(" AND ");
				else sb.append(" WHERE ");
				search=true;
				sb.append("genre='"+genresSearch.getSelectedItem()+"'");				
			}
			sb.append(Film.GROUP_BY);
			//sb.append((specials_button.isSelected())?Film.GROUP_BY_SPECIALS:Film.GROUP_BY);
			sb.append(Film.ORDER_BY);
			String qry = new String();
			qry = sb.toString();
			return qry;
		}
		
		/**
		 * Affiche les données d'une requête sql dans une JTable
		 * @param q requête à exécuter
		 */
		public void displayQueryResults(final String q) {
			MainGui.statusBar.setText("Contacting database...");

			EventQueue.invokeLater(new Runnable() {
				public void run() {
					try {
						table.setModel(factory.getResultSetTableModel(q));
						
				        sorter = new TableSorter(table.getModel());
				        if(storeSort!=null){
				        	sorter.setSortingColumns(storeSort);
				        }
				        
				        table.setModel(sorter);
				        sorter.setTableHeader(table.getTableHeader());
				        table.getTableHeader().setToolTipText(MessagesCommons.getString("window.messages.tri"));
						
				        TableColumnModel columnModel = table.getColumnModel();
						columnModel.getColumn(0).setPreferredWidth(40);
						columnModel.getColumn(0).setMinWidth(40);
						columnModel.getColumn(0).setMaxWidth(40);
						columnModel.getColumn(3).setPreferredWidth(120);
						columnModel.getColumn(3).setMinWidth(120);
						columnModel.getColumn(3).setMaxWidth(120);
						columnModel.getColumn(4).setPreferredWidth(20);
						columnModel.getColumn(4).setMinWidth(20);
						columnModel.getColumn(4).setMaxWidth(20);						

						Object[] titleArgs = {FilmzMain.collection.getNom(), table.getRowCount()};
						//setTitle(Messages.getString("window.movies.titles.list")+" ("+table.getRowCount()+")");
						setTitle(MessageFormat.format(
								Messages.getString("window.movies.titles.list"), titleArgs)
								);

						MainGui.verifUnicite(LIST_NAME, null);
						MainGui.statusBar.setText("");
					} 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("");					
					}
				}
			});
		}	
	
		/**
		 * Affiche la fenêtre d'ajout de film
		 * Utile pour appels depuis une classe 
		 * externe (notamment pour le raccourci d'ajout
		 * de film)
		 */
		public void ajoute(){
			nouveauFilm();
		}
		
		@Override
		protected void popupActions(ActionEvent event){
			String command = event.getActionCommand();
			if(command.equals("new")){
				if(MainGui.verifUnicite(NEW_NAME,null)){
					nouveauFilm();
				}
			}else if(command.equals("del")){
				supprimeFilm(id_selected);
			}else if(command.equals("detailled")){
				if(MainGui.verifUnicite("film_"+id_selected,null)){
					modifieFilm(id_selected);
				}
			}else if(command.equals("web")){
				if(MainGui.verifUnicite("web_film_"+id_selected,null)){
					film = new Film(id_selected);
					new RechercheWeb(film.getTitre(), film);
				}				
			}
		}	
	}
}
