package clientIHM;

import java.awt.GridLayout;
import java.awt.event.*;

import javax.swing.*;

import client.ClientGestTopics;
import clientIHM.ChatterIHM.SessionState;

public class GestConnectionIHM extends JDialog implements ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JButton connectButton;
	JButton cancelButton;
	JTextField servAdrField;
	JTextField portField;
	JTextField errorField;
	ClientGestTopics gt;
	ChatterIHM chatterIHM;
	
	public GestConnectionIHM (ClientGestTopics gt, ChatterIHM chatterIHM) {
		setTitle("Configuration connection");
		this.setSize(400,300);
		this.gt = gt;
		this.chatterIHM = chatterIHM;
		// buttons
		connectButton = new JButton("Connect");
		connectButton.addActionListener(this);
		cancelButton = new JButton("Cancel");
		cancelButton.addActionListener(this);
		
		JPanel buttons= new JPanel();
		buttons.add(cancelButton);
		buttons.add(connectButton);
		this.add(buttons,"Center");
		
		// textfields
		JPanel texts = new JPanel();
		servAdrField = new JTextField("localhost");
		JPanel zoneServ = new JPanel();
		zoneServ.add(new JLabel("Server Address :"));
		zoneServ.add(servAdrField);
		
		JPanel zonePort = new JPanel();
		portField = new JTextField("1664");
		zonePort.add(new JLabel("Server Address :"));
		zonePort.add(portField);
		
		texts.setLayout(new GridLayout(2,1));
		texts.add(zoneServ);
		texts.add(zonePort);
		this.add(texts,"North");
		
		errorField = new JTextField ();
		this.add(errorField,"South");
	}
	
	public void actionPerformed(ActionEvent ev) {
		// TODO Auto-generated method stub
		if (ev.getSource() == connectButton) {
			System.out.println("connection asked for !");
			try {
				gt.setServer(servAdrField.getText(),Integer.parseInt(portField.getText()));
				gt.connect();
				chatterIHM.setState(SessionState.CONNECTED);
				this.setVisible(false);
			} catch (Exception e) {
				errorField.setText("Connection error :" +e);
			}
		} else if (ev.getSource() == cancelButton) {
			this.setVisible(false);
		}
	}


	
}
