package loginModule;
import java.net.*;
import utility.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class LoginAgent extends JInternalFrame
{

	public LoginClientHandler cliHandler = null;
  	public static AgentIdentity id = null;
	String host = "127.0.0.1";
	int port =7000 ;
	String loginName = null;
	String password = null;

	Container frameContainer;
	JPanel jpanel ;
	JTextField logNameText = new JTextField(10);
	JPasswordField passwordText = new JPasswordField(10);
	JTextField svrNameText = new JTextField(10);
	JTextField portNoText = new JTextField(10);
	JButton okBtn = new JButton("OK");
	JButton clrBtn = new JButton("Clear");
	Label nameLbl = new Label("Login Name");
	Label passwdLbl = new Label("Password");
	Label svrNameLbl = new Label("Server IP ");
	Label portNoLbl = new Label("Port No.");

	protected EventListenerList changeListeners = new EventListenerList() ;

	public void doThis()
	{
		boolean success = false;

		if(host != null && port!=0 && loginName != null && password != null )
		{
			try
			{
				Socket srvConn = new Socket(host, port);
        			synchronized (srvConn.getOutputStream())
				{

					System.out.println("Starting login Client Agent :");
					cliHandler = new LoginClientHandler(srvConn.getInputStream(),srvConn.getOutputStream());
					cliHandler.addChangeListener(new CliHandlerAdaptor());
					System.out.println("Got socket to loginServer server :");
					LoginInfo logInfo = new LoginInfo(loginName,password);
					Request req = new Request(logInfo,"LoginInfo");
					ClientHeader toBeSent = new ClientHeader(req);
					success=cliHandler.sendRequest(toBeSent);
				}
			}
      			catch (Exception e)
			{
        			success = false;
      				e.printStackTrace();
			}
		}
		if(!success)
		{
			System.out.println("couldn't send login information");
			//System.exit(1);
			JOptionPane.showMessageDialog(this,"couldn't send login information.","error",JOptionPane.ERROR_MESSAGE);
		}
	}


	public LoginAgent()
	{

		super("Log in",true,true,false,true);
		buildGUI();
		setupEventHandlers();
		setLF();
	}
	void buildGUI()
	{
		jpanel = new JPanel();
		jpanel.setLayout(new BorderLayout());
		frameContainer = getContentPane();
		frameContainer.setLayout(new BorderLayout());

		JPanel panel = new JPanel();
		JPanel lowerPanel = new JPanel();
		panel.setLayout(new GridLayout(4,5));
		lowerPanel.setLayout(new GridLayout(1,5));

		panel.add(Box.createHorizontalStrut(2));
		panel.add(nameLbl);
		panel.add(Box.createHorizontalStrut(1));
		panel.add(logNameText);
		panel.add(Box.createHorizontalStrut(2));
		panel.add(Box.createHorizontalStrut(2));
		panel.add(passwdLbl);
		panel.add(Box.createHorizontalStrut(1));
		svrNameText.setText(host);
		portNoText.setText(String.valueOf(port));
		passwordText.setEchoChar('*');
		panel.add(passwordText);
		panel.add(Box.createHorizontalStrut(2));
		panel.add(Box.createHorizontalStrut(2));
		panel.add(svrNameLbl);
		panel.add(Box.createHorizontalStrut(1));
		panel.add(svrNameText);
		panel.add(Box.createHorizontalStrut(2));
		panel.add(Box.createHorizontalStrut(2));
		panel.add(portNoLbl);
		panel.add(Box.createHorizontalStrut(1));
		panel.add(portNoText);
		panel.add(Box.createHorizontalStrut(2));
		
		lowerPanel.add(Box.createHorizontalStrut(2));
		lowerPanel.add(okBtn);
		lowerPanel.add(Box.createHorizontalStrut(2));
		lowerPanel.add(clrBtn);
		lowerPanel.add(Box.createHorizontalStrut(2));
		
		//lowerPanel.add(Box.createVerticalStrut(0));

		jpanel.add(panel,BorderLayout.CENTER);
		jpanel.add(lowerPanel,BorderLayout.SOUTH);

		frameContainer.add(jpanel,BorderLayout.CENTER);
		setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
	}
	void setupEventHandlers()
	{
		//addWindowListener(new WindowHandler());
		okBtn.addActionListener(new okButtonHandler());
		clrBtn.addActionListener(new clrButtonHandler());
	}


	void setLF()
	{
		String laf = UIManager.getSystemLookAndFeelClassName();
		try
		{
			UIManager.setLookAndFeel(laf);
		}
		catch (UnsupportedLookAndFeelException exc)
		{
			System.err.println("Unsupported: " + laf);
		}
		catch (Exception exc)
		{
			System.err.println("Error loading " + laf);
		}
	}

	public class okButtonHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			host = svrNameText.getText();
			try
			{
      				port = Integer.parseInt(portNoText.getText());
    			}
    			catch (NumberFormatException ex)
			{
				System.out.println("Invalid Port no.");
			}
			loginName =logNameText.getText();
			password =new String (passwordText.getPassword());
			//setVisible(false);
			doThis();



		}
	}
	public class clrButtonHandler implements ActionListener
	{
		public void actionPerformed(ActionEvent e)
		{
			svrNameText.setText("");
			portNoText.setText("");
			logNameText.setText("");
			passwordText.setText("");
		}
	}


	private  class CliHandlerAdaptor implements ChangeListener
		{
			public void stateChanged(ChangeEvent e)
			{
				fireChange();
			}
	}


	public void addChangeListener(ChangeListener x)
	{
		changeListeners.add (ChangeListener.class, x);

	}
	public void removeChangeListener(ChangeListener x)
	{
		changeListeners.remove (ChangeListener.class, x);
	}
	protected void fireChange()
	{

		ChangeEvent c = new ChangeEvent(this);

		Object[] listeners = changeListeners.getListenerList();

		for (int i = listeners.length-2; i >= 0; i -= 2)
		{
			try
			{

				if (listeners[i] == ChangeListener.class)
				{
					ChangeListener cl = (ChangeListener)listeners[i+1];
					cl.stateChanged(c);
				}
			}
			catch(ArrayIndexOutOfBoundsException ex)
			{
					JOptionPane.showMessageDialog(null,ex+" : loginAgent Fire Change");
			}
		}
	}

	public  void logOff()
	{
		if (cliHandler != null && id != null)
		{
			System.out.println("Sending logOff req login server ");
			cliHandler.logOff(id);
		}
		else
			System.out.println("cudn't send  logOff req to login server ");
	}





	public AgentIdentity getIdentity()
  	{
		return id;
	}


	public static void main(String args[])
	{
		LoginAgent la = new LoginAgent();
		la.setVisible(true);
		la.setSize(345,220);
	}

}
