package view;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

import controller.Controller;
import model.RemoteUser;

public class Interface extends JFrame implements ActionListener, WindowListener {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L; //JFrame stuff

	public Controller controller;
		
	public JLabel Pseudolabel;
	public JTextField PseudotextField;
	
	public JLabel Messagelabel;
	public JTextField MessagetextField;
	
	public JButton RemoteUserButton;
	public JComboBox RemoteUserbox;
	
	//Specifies the look and feel to use. Valid values:
	//null (use the default), "Metal", "System", "Motif", "GTK+"
	final static String LOOKANDFEEL = "System";
	
	public Interface(Controller controller) {
		this.controller = controller;
		this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		this.addWindowListener(new java.awt.event.WindowAdapter() {
		    @Override
		    public void windowClosing(java.awt.event.WindowEvent e) {
		        System.out.println("Window closing");
		    }
		});
			
	}
	
	public Component createComponents() {
		PseudotextField = new JTextField();        //Pseudo setup
		PseudotextField.setColumns(10);
		PseudotextField.addActionListener(this);
		Pseudolabel = new JLabel("Your current username is: " + controller.getMyUser().getPseudo());
		Pseudolabel.setLabelFor(PseudotextField);
		
		RemoteUserButton = new JButton("Click here to get Remote User list");          //Remote user list setup
		RemoteUserButton.addActionListener(this);
		//Convert the Userlist to Pseudotab
		String[] pseudotab = new String[controller.getMyUser().getRemoteUsersList().size()];
		for(int i=0; i < controller.getMyUser().getRemoteUsersList().size(); i++) {
			pseudotab[i] = "(" + Integer.toString(i) + "): " + controller.getMyUser().getRemoteUsersList().get(i).getPseudo();
		}
		RemoteUserbox = new JComboBox(pseudotab);
		RemoteUserbox.setEditable(true);
		RemoteUserbox.addActionListener(this);
		RemoteUserbox.setVisible(false);
		
		MessagetextField = new JTextField();       //Messages setup
		MessagetextField.setColumns(10);
		MessagetextField.addActionListener(this);
		Messagelabel = new JLabel("Message field: ");
		Messagelabel.setLabelFor(MessagetextField);
		MessagetextField.setVisible(false);
		Messagelabel.setVisible(false);
		
		/*
		* An easy way to put space between a top-level container
		* and its contents is to put the contents in a JPanel
		* that has an "empty" border.
		*/
		JPanel pane = new JPanel(new GridLayout(0, 2));
		pane.add(Pseudolabel);
		pane.add(PseudotextField);
		pane.add(RemoteUserButton);
		pane.add(RemoteUserbox);
		pane.add(Messagelabel);
		pane.add(MessagetextField);
		pane.setBorder(BorderFactory.createEmptyBorder(
									30, //top
									30, //left
									10, //bottom
									30) //right
		);
			
		return pane;
	}
	
	public void actionPerformed(ActionEvent e) {
		if(e.getSource() == PseudotextField) {                //Changing pseudo
			String Textinput = PseudotextField.getText();
			Pseudolabel.setText("Your current username is: " + Textinput);
			
			try {
				controller.changePseudo();
			} catch (IOException e1) {
				System.out.println("Error in change pseudo\n");
				e1.printStackTrace();
			}
		}else if(e.getSource() == MessagetextField){          //Messages
			String Textinput = MessagetextField.getText();
			Messagelabel.setText(Messagelabel.getText()+"<br>test" + Textinput);
			MessagetextField.setText("");
			controller.askToSend(Textinput); // ask to send to controller 
			
		}else if(e.getSource() == RemoteUserButton) {         //Shows remote user list
			RemoteUserbox.setVisible(true);
		}else { // Choice in remote user list
			
			JComboBox cb = (JComboBox)e.getSource();          //Casts obscurs pour récupérer le numéro du user dans la liste
			int selectedUsernb = Integer.parseInt(String.valueOf(((String) cb.getSelectedItem()).charAt(1)));

			// start or switch chat => get history 
			String history = controller.askOpenSession(selectedUsernb);
			// display it
			Messagelabel.setText("Message:<br>"+history);
			MessagetextField.setVisible(true);
			Messagelabel.setVisible(true);
		}
	}
	 
	private static void initLookAndFeel() {
		// Swing allows you to specify which look and feel your program uses-
		// -Java,
		// GTK+, Windows, and so on as shown below.
		String lookAndFeel = null;
			
		if (LOOKANDFEEL != null) {
			if (LOOKANDFEEL.equals("Metal")) {
				lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
			} else if (LOOKANDFEEL.equals("System")) {
				lookAndFeel = UIManager.getSystemLookAndFeelClassName();
			} else if (LOOKANDFEEL.equals("Motif")) {
				lookAndFeel = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
			} else if (LOOKANDFEEL.equals("GTK+")) { //new in 1.4.2
				lookAndFeel = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
			} else {
				System.err.println("Unexpected value of LOOKANDFEEL specified: " + LOOKANDFEEL);
				lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
			}	
			try {UIManager.setLookAndFeel(lookAndFeel);
			} catch (ClassNotFoundException e) {
				System.err.println("Couldn't find class for specified look and feel:" + lookAndFeel);
				System.err.println("Did you include the L&F library in the class path?");
				System.err.println("Using the default look and feel.");
			} catch (UnsupportedLookAndFeelException e) {
				System.err.println("Can't use the specified look and feel (" + lookAndFeel+ ") on this platform.");
				System.err.println("Using the default look and feel.");
			} catch (Exception e) {
				System.err.println("Couldn't get specified look and feel (" + lookAndFeel + "), for some reason.");
				System.err.println("Using the default look and feel.");
				e.printStackTrace();
			}
		}
	}
	
	/**
	* Create the GUI and show it. For thread safety,
	* this method should be invoked from the
	* event-dispatching thread.
	*/
	public static Interface createAndShowGUI(Controller controller) {
		//Set the look and feel.
		initLookAndFeel();
		
		//Make sure we have nice window decorations.
		JFrame.setDefaultLookAndFeelDecorated(true);
			
		//Create and set up the window.
		JFrame frame = new JFrame("Clavardage App");
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		
		
		
		Interface app = new Interface(controller);
		Component contents = app.createComponents();
		frame.getContentPane().add(contents, BorderLayout.CENTER);
			
		
		frame.addWindowListener(new java.awt.event.WindowAdapter() {
		    @Override
		    public void windowClosing(java.awt.event.WindowEvent windowEvent) {
		        System.out.println("GUI has been closed");
		        app.controller.interfaceRunning = false;
		       
		        System.exit(0);
		    }
		});	
		
		//Display the window.
		frame.pack();
		frame.setVisible(true);
		
		return app;
	}

	public void windowOpened(WindowEvent e) {} //Had to implement it for WindowListener
    public void windowActivated(WindowEvent e) {}
    public void windowIconified(WindowEvent e) {}
    public void windowDeiconified(WindowEvent e) {}
    public void windowDeactivated(WindowEvent e) {}
    public void windowClosed(WindowEvent e) {}
	public void windowClosing(WindowEvent e) {}

		/*
	public static void main(String[] args) throws IOException {
		//Schedule a job for the event-dispatching thread:
		//creating and showing this application’s GUI.
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				createAndShowGUI();
			}
		});
	}*/
}