package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
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.JRootPane;
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.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;



import model.article.Nomenclature;


import controller.GestionArticle;



public class IHM {

	private static ModelStatiqueArticle modele = new ModelStatiqueArticle();
	public static JTable tableau;
	static JPanel p;
	static Arbre a;
	public final static ConfirmExitDialog f=new ConfirmExitDialog("Magic Penguins");
	//private JDialog popup = new JDialog(IHM.f,"Ajouter",true);

	JPopupMenu menu = new JPopupMenu();
	JPopupMenu menuTableau = new JPopupMenu();

	public IHM() {

		super(); 

		//f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		f.setVisible(true);

		//menu = new JPopupMenu();
		final JMenuItem bouttonAjouter = new JMenuItem("Ajouter");
		menu.add(bouttonAjouter);
		final JMenuItem bouttonSupprimer = new JMenuItem("Supprimer");
		menu.add(bouttonSupprimer);

		//menuTableau = new JPopupMenu();
		//menuTableau = new JPopupMenu();
		final JMenuItem bouttonAjouterArticles = new JMenuItem("Ajouter Article vide");
		menuTableau.add(bouttonAjouterArticles);
		final JMenuItem bouttonSupprimerArticles = new JMenuItem("Supprimer Articles selectionnes");
		menuTableau.add(bouttonSupprimerArticles);
		/*final JMenuItem bouttonAjouterSelectionALaNom = new JMenuItem("Ajouter selection a la nomenclature");
		menuTableau.add(bouttonAjouterSelectionALaNom);*/
		
		

		bouttonSupprimerArticles.addActionListener(new RemoveAction());
		bouttonAjouterArticles.addActionListener(new AddAction());
		//bouttonAjouterSelectionALaNom.addActionListener(new AjouterALaNom());

		tableau = new JTable(modele);
		//tableau.setAutoCreateRowSorter(true);


		//f.pack();


		SelectionListener listener = new SelectionListener(tableau);
		tableau.getSelectionModel().addListSelectionListener(listener);
		tableau.getColumnModel().getSelectionModel().addListSelectionListener(listener);

		//--------------------------------------- Listener Clique droit sur l'arbre --------------------------------------


//ActionsClickDroitAjouter(((Nomenclature)node.getUserObject()).getArticle(),node,a));
		
		MouseAdapter mickey =  new MouseAdapter() {
			public void mouseReleased(MouseEvent e) {

				if(SwingUtilities.isRightMouseButton(e)) {
					//System.out.println("moso");
					//Action a faire
					TreePath selPath = a.getJTree().getPathForLocation(e.getX(), e.getY());

					if (selPath != null) {
						//System.out.println("boah");
						//A partir du chemin, on récupère le noeud 
						DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
						if ((node != null)) {
							//System.out.println("intzz");

							//action a faire
							a.getJTree().setSelectionPath(selPath);
							bouttonSupprimer.addActionListener(new ActionsClickDroit(((Nomenclature)node.getUserObject()).getArticle(),node,a, 0));
							bouttonAjouter.addActionListener(new ActionsClickDroit(((Nomenclature)node.getUserObject()).getArticle(),node,a, 0));
							
							f.pack();
							menu.show(e.getComponent(), e.getX(), e.getY());
							//System.out.println("a");

						}
					}
				}
				else if(e.getClickCount()==2){
					TreePath selPath = a.getJTree().getPathForLocation(e.getX(), e.getY());
					if (selPath != null && selPath.getParentPath() != null) {
						//System.out.println("boah");
						//A partir du chemin, on récupère le noeud 
						final DefaultMutableTreeNode node = (DefaultMutableTreeNode) selPath.getLastPathComponent();
						if ((node != null)) {

						//System.out.println("boaaaaah");
							
							final JFrame Modifier = new JFrame("Modifier la quantite");
							Modifier.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
							Modifier.setLocation(e.getXOnScreen(), e.getYOnScreen());
							Modifier.setSize(300, 100);
							Modifier.setBackground(Color.WHITE);
							Modifier.setUndecorated(true);
							Modifier.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
							Modifier.setVisible(true);
							
							
							
							
							JPanel bob = new JPanel();
							bob.setBackground(Color.WHITE);
							Modifier.add(bob);
							
							JLabel l1 = new JLabel("L'article "+((Nomenclature)((DefaultMutableTreeNode) node.getParent()).getUserObject()).getArticle().getDesignation()+" a besoin de ");
						
							JLabel l2 = new JLabel(" "+((Nomenclature)node.getUserObject()).getArticle().getDesignation());
							
							
							final JTextField t = new JTextField(""+((Nomenclature)node.getUserObject()).getQuantite());
							t.setPreferredSize(new Dimension(40,20));
							t.setForeground(Color.BLUE);
	

							
							bob.add(l1);
							bob.add(t);
							bob.add(l2);
							JButton ok = new JButton("Valider");
							new BorderLayout();
							Modifier.add(ok,BorderLayout.SOUTH);
							ok.addActionListener(new ActionListener() {
								
								@Override
								public void actionPerformed(ActionEvent e) {
									try {
										((Nomenclature)node.getUserObject()).setQuantite(Integer.parseInt(t.getText()));
										a.getJTree().updateUI();
										Modifier.dispose();
									} catch (NumberFormatException nbe) {
										t.setForeground(Color.RED);
									}
									
								}
							});
							
							
							//action a faire
							/*a.getJTree().setSelectionPath(selPath);
							bouttonSupprimer.addActionListener(new ActionsClickDroit(((Nomenclature)node.getUserObject()).getArticle(),node,null,a));
							bouttonAjouter.addActionListener(new ActionsClickDroit(((Nomenclature)node.getUserObject()).getArticle(),node,null,a));
							f.pack();
							menu.show(e.getComponent(), e.getX(), e.getY());
							System.out.println("a");*/

						}
					}
					
				}
			}
		};


		//--------------------------------------- Listener Clique droit sur le tableau --------------------------------------

		MouseAdapter mickeyTableau =  new MouseAdapter() {
			public void mouseReleased(MouseEvent e) {

				if(SwingUtilities.isRightMouseButton(e)) {
					//System.out.println("moso");
					//Action a faire

					//System.out.println("boah");
					int[] Index = tableau.getSelectedRows();

					if ((Index != null)) {
						//System.out.println("intzz");
						//action a faire
						f.pack();
						menuTableau.show(e.getComponent(), e.getX(), e.getY());
					//System.out.println("a");

					}
				}



			}
		}
		;


		p = new JPanel();
		p.setBackground(Color.WHITE);

		JPanel haut = new JPanel();

		f.add(haut, BorderLayout.CENTER);
		haut.setLayout(new GridLayout(1,2));

		//p.add(a.getJTree());
		haut.add(new JScrollPane(tableau));
		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);


		menuItemCharger.addActionListener(new ChargerArticle());
		menuItemSauvegarder.addActionListener(new SauvegarderArticle());
		
		JMenu menuFichier2 = new JMenu("A propos");
		menuFichier2.setMnemonic(KeyEvent.VK_A);
		menuBar.add(menuFichier2);

		JMenuItem menuItem2a = new JMenuItem("Le monde des pinguins.com");
		menuItem2a.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_1, ActionEvent.ALT_MASK));
		menuFichier2.add(menuItem2a);

		JMenuItem menuItem2b = new JMenuItem("Les pinguins pour les nuls");
		menuItem2b.setAccelerator(KeyStroke.getKeyStroke(
				KeyEvent.VK_1, ActionEvent.ALT_MASK));
		menuFichier2.add(menuItem2b);

		f.setJMenuBar(menuBar);

		//-----------------------------------------------------------------------------------------------------

		tableau.addMouseListener(mickeyTableau);
		
		a = new Arbre(new JTree(), mickey);
		a.getJTree().setPreferredSize(new Dimension(500,500));
		a.getJTree().setVisible(true);
		p.add(a.getJTree());

		
		
	}



	//========================================================== MAIN =======================================================

	public static void main(String[] args) {
		@SuppressWarnings("unused")
		GestionArticle gestionArticle = new GestionArticle();
		new IHM();
		GestionArticle.restaurerArticles();
		modele.reconstruireTableau();
		if(tableau.getRowCount()>0) tableau.setRowSelectionInterval(0, 0);
	}

	//================================================== Classes Listener ===============================================================

	private class AddAction extends AbstractAction {

		private static final long serialVersionUID = -4710678094605723981L;

		private AddAction() {
			super("Ajouter Article");
		}

		public void actionPerformed(ActionEvent e) {
			modele.addArticle(0,/* 0,*/ 0);
		}
	}


	private class SauvegarderArticle extends AbstractAction {

		private static final long serialVersionUID = -4710678094605723981L;

		private SauvegarderArticle() {
			super("Sauvegarder articles");
		}

		public void actionPerformed(ActionEvent e) {
			int n = JOptionPane.showConfirmDialog(f, "Ecraser les donnees ou pinguins enregistres ?", "Sauvegarde", JOptionPane.YES_NO_OPTION);
			if(n==0) GestionArticle.sauvegarderArticles();
		}
	}


	private class ChargerArticle extends AbstractAction {

		private static final long serialVersionUID = -4710678094605723981L;

		private ChargerArticle() {
			super("Charger articles");
		}

		public void actionPerformed(ActionEvent e) {
			modele.supprimerTableau();
			GestionArticle.restaurerArticles();
			modele.reconstruireTableau();

			if(tableau.getRowCount()>0) tableau.setRowSelectionInterval(0, 0);
		}
	}
	
	/*private class AjouterALaNom extends AbstractAction {

		private static final long serialVersionUID = -4710678094605723981L;

		private AjouterALaNom() {
			super("Ajouter a la nomenclature");
		}

		public void actionPerformed(ActionEvent e) {
			modele.supprimerTableau();
			GestionArticle.restaurerArticles();
			modele.reconstruireTableau();

			if(tableau.getRowCount()>0) tableau.setRowSelectionInterval(0, 0);
		}
	}*/



	private class RemoveAction extends AbstractAction {

		private static final long serialVersionUID = -8245474173854122493L;

		private RemoveAction() {
			super("Supprimmer selection");
		}

		public void actionPerformed(ActionEvent e) {
			int[] selection = tableau.getSelectedRows();
			int[] modelIndexes = new int[selection.length];

			/*for(int i = 0; i < selection.length; i++){
				modelIndexes[i] = tableau.getRowSorter().convertRowIndexToModel(selection[i]);
			}*/
			for(int i = 0; i < selection.length; i++){
				modelIndexes[i] = selection[i];
			}

			//Arrays.sort(modelIndexes);

			for(int i = modelIndexes.length - 1; i >= 0; i--){

				//modele.removeArticle(tableau.getRowSorter().convertRowIndexToModel(modelIndexes[i]));
				modele.removeArticle(modelIndexes[i]);
			}
		}
	}
}




