package gui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.SystemColor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.JComboBox;
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.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.UIManager;

import controller.Agent;
import server.Request;

public class FenetreMenu {
	
	JFrame frame;
    JPanel panel;
    JMenuBar menu;
    Agent agent;
    JLabel jlabel;
    JLabel texte;
    JLabel liste;
    JLabel vide;
    static JComboBox cb;
    WindowAdapter wa ;
    
    public static boolean ouvert = false;
    
    public FenetreMenu(Agent agent) throws IOException {
    	FenetreMenu.ouvert=true;
    	this.agent = agent;
    	    try {
    	            UIManager.setLookAndFeel("com.jtattoo.plaf.noire.NoireLookAndFeel");
    	 
    	        } catch (ClassNotFoundException ex) {
    	            java.util.logging.Logger.getLogger(FenetreMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    	        } catch (InstantiationException ex) {
    	            java.util.logging.Logger.getLogger(FenetreMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    	        } catch (IllegalAccessException ex) {
    	            java.util.logging.Logger.getLogger(FenetreMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    	        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
    	            java.util.logging.Logger.getLogger(FenetreMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    	        }
    	    
    	frame = new JFrame("Fenêtre menu");
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		
		frame.setSize(new Dimension(600, 800));
		frame.setResizable(false);
		 
		wa = new WindowAdapter(){
	            public void windowClosing(WindowEvent e){
	                  int reponse = fenetreFermeture();
	                  if (reponse==0){
	                	  	 try {
	                	  		 // on deconnecte l'app avant de quitter 
	                	  		 // Tout les utilisateurs sont donc prevenus du depart
								agent.deconnexion();
							} catch (IOException e1) {
								e1.printStackTrace();
							}
	                          frame.dispose();
	                  }
	            }};
	            
	            
	        frame.addWindowListener(wa); 
	        menu = new JMenuBar();
	        
	        //Creation d'un JPanel
	    	panel = new JPanel(new GridBagLayout());
	    	panel.setForeground(SystemColor.menuText);
	    	panel.setOpaque(false);
	    	
	    	// Ajouter tout les elements a la fenetre
	        this.addWidgets();
	        
	        try {
                final Image backgroundImage = javax.imageio.ImageIO.read(new File("background2.jpg"));
                frame.setContentPane(new JPanel(new BorderLayout()) {
                    @Override public void paintComponent(Graphics g) {
                        g.drawImage(backgroundImage, 0, 0, null);
                    }
                });
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
	        
	        // ajouter le panel a la fenetre
	        frame.getContentPane().add(panel, BorderLayout.CENTER);
	        
	        // Afficher la fenetre
	        frame.pack();
	        frame.setVisible(true);
		}
    
    static int fenetreFermeture() {
    	return JOptionPane.showConfirmDialog(
 		       null,
 		       "Are you sure you wanna quit?",
 		       "Quitter",
 		       JOptionPane.YES_NO_OPTION);
    }
    
    private void addWidgets() throws IOException {
    	
    	jlabel = new JLabel(new ImageIcon("panda.png"), JLabel.CENTER);
    	jlabel.setOpaque(false);
    	texte = new JLabel();
        texte.setOpaque(false);
        texte.setFont(new Font("Century Schoolbook", Font.PLAIN, 60));
        texte.setText("<html><font color = #F7F9F9>Bienvenue sur le tchat</font></html>");
        texte.setHorizontalAlignment(SwingConstants.CENTER);
        liste = new JLabel("Active users", JLabel.LEFT);
        liste.setOpaque(false);
	 	
        vide = new JLabel();
        vide.setOpaque(false);
        
        Color c = new Color(25, 94, 125);
        
	 	JMenu contenu = new JMenu("Actions");
	 	contenu.setForeground(Color.WHITE);
	 	contenu.setBackground(c.darker());
	 	contenu.setHorizontalAlignment(SwingConstants.CENTER);
    
	 	JMenuItem modifierPseudo = new JMenuItem("Modify your pseudo");
	 	modifierPseudo.setBackground(c.darker());
	 	modifierPseudo.setForeground(Color.WHITE);
	    JMenuItem deco = new JMenuItem("Deconnection");
	    deco.setBackground(c.darker());
	    deco.setForeground(Color.WHITE);
	      
	    contenu.add(modifierPseudo);
	    contenu.add(deco);
	    
	    menu.setBackground(c);
	    menu.add(contenu);
	    frame.setJMenuBar(menu);
	    
	    /*liste déroulante des utilsateurs actifs, 
	     * cliquer dessus pour créer une fenêtre de chat*/
	    JTextArea ta = new JTextArea(20,20);
   		ta.insert("Active users\n",0);
		JScrollPane scrollPane = new JScrollPane(ta); 
		
		String users = Request.actifs("actifs");
		String users2 = users.replaceAll("\\s", "\n");
	    Vector<String> v = new Vector<String>();
		for(String pseudo : users2.split("\n")) {
   			v.add(pseudo);
   		 }
		
		cb = new JComboBox(v);
		cb.setSelectedItem(agent.getUser().getPseudo());
		cb.setBackground(c);
		cb.setForeground(Color.WHITE);
		cb.setFocusable(false);
  	    cb.addActionListener(new ActionListener() {
  	    	public void actionPerformed(ActionEvent event) {
                Object selected = cb.getSelectedItem();
                int idDest = agent.getDb().getIdFromPseudo(selected.toString());
                try {
					agent.createChat(idDest, selected.toString());
				} catch (IOException e) {
					System.out.println("Creation tcp chat impossible");
					e.printStackTrace();
				}
                try {
                		FenetreChat.getInstance(agent, selected.toString());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
                cb.setSelectedItem(agent.getUser().getPseudo());

            }
  	    });
  	    cb.setPreferredSize(new Dimension(500, 30));
  	    
  	    
  	    GridBagConstraints con = new GridBagConstraints();
  	    Insets i = new Insets(150, 0, 5, 0);
	  	con.weightx = 200;
	  	con.gridx = 1;
	  	con.gridy = 0;
	  	 
	  	panel.add(jlabel, con);
	  	
	  	con.weightx = 100;
	  	con.gridx=1;
	  	con.gridy=1;
	  	panel.add(texte, con);
	  	
	  	
	  	con.weightx=50;
	  	con.fill = GridBagConstraints.HORIZONTAL;
	  	con.gridx=1;
	  	con.gridy = 3;
	  	con.insets = i;
	  	panel.add(cb, con);
	  	  
	  	  
	  	
  	    
  	    /*actions pour modifier le pseudo*/
	  	  
	  	modifierPseudo.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                frame.dispose();
                new FenetreModifPseudo(agent);
            }
        });
	  	  
  	    
	    deco.addActionListener(new ActionListener() {
	    	public void actionPerformed(ActionEvent e) {
	    		try {
					agent.deconnexion();
					frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
				} catch (IOException e1) {
					System.out.println("Deconnexion impossible");
					e1.printStackTrace();
				}
	    	}
	    });
	 	
	 	
	 	
    }
    
    public static JComboBox getCb() {
    	return cb;
    }
}
    
  	 