package view.article;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import view.MainFrame;

import model.article.Nomenclature;
import model.gammeOperatoire.GammeOperatoire;

import controller.BaseDonnees;

/**
 * 
 * @author Magic Penguins
 * @see MainFrame
 *
 */

public class IHM {

	public static ModelStatiqueArticle modele = new ModelStatiqueArticle();
	public static JTable tableau;
	static JPanel p;
	static Arbre a;

	static JPanel GlobalContainer = new JPanel();


	static JPopupMenu menu = new JPopupMenu();
	static JPopupMenu menuTableau = new JPopupMenu();

	/**
	 * Cree un panel contenant la {@link JTable} et le {@link JTree} representant les differents articles et leur nomenclature 
	 * @return Panel de retour
	 */
	public static Component CreerContainer() {

		final JMenuItem bouttonAjouter = new JMenuItem("Ajouter");
		menu.add(bouttonAjouter);
		final JMenuItem bouttonSupprimer = new JMenuItem("Supprimer");
		menu.add(bouttonSupprimer);



		final JMenuItem bouttonAjouterArticles = new JMenuItem("Ajouter Article vide");
		menuTableau.add(bouttonAjouterArticles);
		final JMenuItem bouttonSupprimerArticles = new JMenuItem("Supprimer Articles selectionnes");
		menuTableau.add(bouttonSupprimerArticles);



		bouttonSupprimerArticles.addActionListener(new RemoveAction());
		bouttonAjouterArticles.addActionListener(new AddAction());

		tableau = new JTable(modele);

		int vColIndex = 4;
		TableColumn col = tableau.getColumnModel().getColumn(vColIndex);
		Vector<GammeOperatoire> tmp = new Vector<GammeOperatoire>();
		tmp = BaseDonnees.listeGammes;
		tmp.add(0,null);
		col.setCellEditor(new MyComboBoxEditor(BaseDonnees.listeGammes));


		SelectionListener listener = new SelectionListener(tableau);
		tableau.getSelectionModel().addListSelectionListener(listener);
		tableau.getColumnModel().getSelectionModel().addListSelectionListener(listener);

		//--------------------------------------- Listener Clique droit sur l'arbre --------------------------------------

		a = new Arbre(new JTree());
		a.getJTree().setPreferredSize(new Dimension(500,500));
		a.getJTree().setVisible(true);


		final ActionsClickDroit click = new ActionsClickDroit(a);
		bouttonSupprimer.addActionListener(click);
		bouttonAjouter.addActionListener(click);

		MouseAdapter mickey =  new MouseAdapter() {
			public void mouseReleased(MouseEvent e) {

				if(SwingUtilities.isRightMouseButton(e)) {
					//Action a faire
					TreePath selPath = a.getJTree().getPathForLocation(e.getX(), e.getY());

					if (selPath != null) {

						//A partir du chemin, on recupere le noeud 
						DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
						if ((node != null)) {

							//action a faire
							a.getJTree().setSelectionPath(selPath);
							click.setParam(((Nomenclature)node.getUserObject()).getArticle(),node);


							a.getJTree().updateUI();
							menu.show(e.getComponent(), e.getX(), e.getY());

						}
					}
				}
				else if(e.getClickCount()==2){
					TreePath selPath = a.getJTree().getPathForLocation(e.getX(), e.getY());
					if (selPath != null && selPath.getParentPath() != null) {

						//A partir du chemin, on recupere le noeud 
						final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
						if ((node != null)) {

							JPanel bob = new JPanel();
							bob.setLayout(new BoxLayout(bob, BoxLayout.PAGE_AXIS));

							JPanel globalPane = new JPanel();


							JLabel l1 = new JLabel("L'article "+((Nomenclature)((DefaultMutableTreeNode) node.getParent()).getUserObject()).getArticle().getDesignation()+" a besoin de ");

							JLabel l2 = new JLabel(" "+((Nomenclature)node.getUserObject()).getArticle());


							final JTextField t = new JTextField(""+((Nomenclature)node.getUserObject()).getQuantite());
							t.setPreferredSize(new Dimension(40,20));

							globalPane.add(t);
							globalPane.add(l2);


							bob.add(l1);
							bob.add(globalPane);
							new BorderLayout();			

							int res = JOptionPane.showConfirmDialog(MainFrame.f, bob, "Ajout d'acrticle a la nomenclature", JOptionPane.OK_CANCEL_OPTION);
							if (res == JOptionPane.OK_OPTION) {
								try {
									if (t.getText().trim().length() == 0) {
										JOptionPane.showMessageDialog(MainFrame.f, "Veuillez remplir tout les champs", "Erreur",JOptionPane.ERROR_MESSAGE);
										mouseReleased(e);
									}
									else {
										int quantite = Integer.parseInt(t.getText());
										((Nomenclature)node.getUserObject()).setQuantite(quantite);
										a.getJTree().updateUI();


									}
								} catch (NumberFormatException nbe) {
									JOptionPane.showMessageDialog(MainFrame.f, "Erreur dans le format d'entree", "Erreur",JOptionPane.ERROR_MESSAGE);
									mouseReleased(e);
								}
							}
						}
					}

				}
			}
		};

		a.setMouseAdaptater(mickey);


		//--------------------------------------- Listener Clique droit sur le tableau --------------------------------------

		MouseAdapter mickeyTableau =  new MouseAdapter() {
			public void mouseReleased(MouseEvent e) {

				if(SwingUtilities.isRightMouseButton(e)) {

					tableau.updateUI();
					menuTableau.show(e.getComponent(), e.getX(), e.getY());
				}
			}
		};

		p = new JPanel();
		p.setBackground(Color.WHITE);

		JPanel haut = new JPanel();

		GlobalContainer.add(haut, BorderLayout.CENTER);
		haut.setLayout(new GridLayout(1,2));

		JPanel hautGauche = new JPanel();

		hautGauche.add(new JScrollPane(tableau));
		tableau.addMouseListener(mickeyTableau);
		hautGauche.addMouseListener(mickeyTableau);

		haut.add(hautGauche);
		haut.add(new JScrollPane(p));


		JMenuBar menuBar = new JMenuBar();

		JMenu menuFichier1 = new JMenu("Fichier");
		menuFichier1.setMnemonic(KeyEvent.VK_A);
		menuBar.add(menuFichier1);

		JMenuItem menuItemSauvegarder = new JMenuItem("Sauvegarder");
		menuItemSauvegarder.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		menuFichier1.add(menuItemSauvegarder);


		JMenuItem menuItemCharger = new JMenuItem("Charger");
		menuItemCharger.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
		menuFichier1.add(menuItemCharger);

		JMenuItem menuItemNouvelArticle = new JMenuItem("Nouvel article");
		menuItemNouvelArticle.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
		menuFichier1.add(menuItemNouvelArticle);


		menuItemCharger.addActionListener(new ChargerArticle());
		menuItemSauvegarder.addActionListener(new SauvegarderArticle());
		menuItemNouvelArticle.addActionListener(new AddAction());

		JMenu menuFichier2 = new JMenu("A propos");
		menuFichier2.setMnemonic(KeyEvent.VK_A);
		menuBar.add(menuFichier2);

		JMenuItem menuItem2a = new JMenuItem("Les pingouins sont nos amis");
		menuItem2a.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_1, ActionEvent.ALT_MASK));
		menuFichier2.add(menuItem2a);

		JMenuItem menuItem2b = new JMenuItem("Il faut les aimer aussi");
		menuItem2b.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_1, ActionEvent.ALT_MASK));
		menuFichier2.add(menuItem2b);

		MainFrame.f.setJMenuBar(menuBar);

		if (tableau.getRowCount()> 0) {tableau.getSelectionModel().setSelectionInterval(0, 0);}
		p.add(a.getJTree());
		return GlobalContainer;
	}
}



class MyComboBoxRenderer extends JComboBox implements TableCellRenderer {

	private static final long serialVersionUID = 1L;

	public MyComboBoxRenderer(Vector<GammeOperatoire> listeGammes) {
		super(listeGammes);
	}


	public Component getTableCellRendererComponent(JTable table, Object value,boolean isSelected, boolean hasFocus, int row, int column) {

		if(value == null) setSelectedIndex(-1);

		else setSelectedItem(value);
		return this;
	}
}

class MyComboBoxEditor extends DefaultCellEditor {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public MyComboBoxEditor(Vector<GammeOperatoire> listeGammes) {
		super(new JComboBox(listeGammes));
	}
}

//================================================== Classes Listener ===============================================================

class AddAction extends AbstractAction {

	private static final long serialVersionUID = -4710678094605723981L;

	AddAction() {
		super("Ajouter Article");
	}

	public void actionPerformed(ActionEvent e) {
		IHM.modele.addArticle(0, 0);
	}
}


class SauvegarderArticle extends AbstractAction {

	private static final long serialVersionUID = -4710678094605723981L;

	SauvegarderArticle() {
		super("Sauvegarder articles");
	}

	public void actionPerformed(ActionEvent e) {
		int n = JOptionPane.showConfirmDialog(MainFrame.f, "Ecraser les donnees ou pinguins enregistres ?", "Sauvegarde", JOptionPane.YES_NO_OPTION);
		if(n==0) BaseDonnees.sauvegarder();
	}
}


class ChargerArticle extends AbstractAction {

	private static final long serialVersionUID = -4710678094605723981L;

	ChargerArticle() {
		super("Charger articles");
	}

	public void actionPerformed(ActionEvent e) {
		IHM.modele.supprimerTableau();
		BaseDonnees.restaurer();
		IHM.modele.reconstruireTableau();

		if(IHM.tableau.getRowCount()>0) IHM.tableau.setRowSelectionInterval(0, 0);
	}
}

class RemoveAction extends AbstractAction {

	private static final long serialVersionUID = -8245474173854122493L;

	RemoveAction() {
		super("Supprimmer selection");
	}

	public void actionPerformed(ActionEvent e) {
		int[] selection = IHM.tableau.getSelectedRows();
		int[] modelIndexes = new int[selection.length];

		for(int i = 0; i < selection.length; i++){
			modelIndexes[i] = selection[i];
		}


		for(int i = modelIndexes.length - 1; i >= 0; i--){

			IHM.modele.removeArticle(modelIndexes[i]);
		}
	}
}





