/*
 * AirportBaseStationHangup Utility
 *
 * Copyright (C) 2000, Jonathan Sevy <jsevy@mcs.drexel.edu>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */



import java.util.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.plaf.*;
import java.awt.event.*;
import java.io.*;




public class AirportBaseStationHangup extends JFrame
							implements ActionListener, Runnable, WindowListener
{
	
	JButton hangupModemButton, connectModemButton, newHostButton;
	JTextArea messagesArea;
	JScrollPane messagesScroll;
	JTextField hostIDField, modemStatusField, timeField;
	JLabel authorLabel, hostIDLabel, modemStatusLabel, timeLabel, connectTimeCaveatLabel;
	
	MenuBar theMenubar;
	Menu fileMenu;
	MenuItem quitItem;
	
	InetAddress hostAddress;
	
	DatagramSocket dSocket;
	final int OSU_NMS_PORT = 192;	
	
	boolean minimized;
	
	Thread statusThread;
			
	
	
			
	
	public AirportBaseStationHangup(String defaultIPAddress)
	throws Exception
	{
		setUpDisplay(defaultIPAddress);
		
		hostAddress = InetAddress.getByName(hostIDField.getText());
			
		dSocket = new DatagramSocket();
		dSocket.setSoTimeout(2000);	// 2 seconds
		
		statusThread = new Thread(this);
		statusThread.start();
		
	}
	
	
	
	
	private void setUpDisplay(String defaultIPAddress)
	{
		
		
		try
		{
			// set look-and-feel to native platform l&f, if possible
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch(Exception e)
		{
			// or not...
		}

		
		this.getRootPane().setBorder(new BevelBorder(BevelBorder.RAISED));
		
		// set fonts to smaller-than-normal size, for compaction!
		
		FontUIResource appFont = new FontUIResource("SansSerif", Font.PLAIN, 10);
		UIDefaults defaults = UIManager.getLookAndFeelDefaults();
		Enumeration keys = defaults.keys();
		
		while (keys.hasMoreElements())
		{
			String nextKey = (String)(keys.nextElement());
			if ((nextKey.indexOf("font") > -1) || (nextKey.indexOf("Font") > -1))
			{
			    UIManager.put(nextKey, appFont);
			}
		}
		
		
		// register self as WindowListener, to catch minimization events
		addWindowListener(this);
		
		/*
		theMenubar = new MenuBar();
		this.setMenuBar(theMenubar);
		fileMenu = new Menu("File");
		
		quitItem = new MenuItem("Quit");
		quitItem.setActionCommand("quit");
		quitItem.addActionListener(this);
		fileMenu.add(quitItem);
		
		theMenubar.add(fileMenu);
		*/
		
		hostIDLabel = new JLabel("Address:");
		hostIDField = new JTextField(10);
		hostIDField.setText(defaultIPAddress);
		hostIDField.setEditable(false);
		
		modemStatusLabel = new JLabel("Connection status:");
		modemStatusField = new JTextField(16);
		modemStatusField.setEditable(false);
		
		timeLabel = new JLabel("Connection time:");
		timeField = new JTextField(16);
		timeField.setEditable(false);
		
		authorLabel = new JLabel(" Version 1.5        J. Sevy, March 2002");
		authorLabel.setFont(new Font("SansSerif", Font.ITALIC, 8));
			
		
		hangupModemButton = new JButton("Disconnect");
		//hangupModemButton.setPreferredSize(new Dimension(100, 20));
		hangupModemButton.setActionCommand("hangup modem");
		hangupModemButton.addActionListener(this);
		
		connectModemButton = new JButton("Connect");
		//connectModemButton.setPreferredSize(new Dimension(100, 20));
		connectModemButton.setActionCommand("connect modem");
		connectModemButton.addActionListener(this);
		
		newHostButton = new JButton("Set address");
		newHostButton.setActionCommand("new host");
		newHostButton.addActionListener(this);
		
		messagesArea = new JTextArea(3,30);
		messagesScroll = new JScrollPane(messagesArea);
		 
		
        //URL url = AirportBaseStationHangup.class.getResource("iconImage.gif");
		//this.setIconImage(Toolkit.getDefaultToolkit().getImage(url));
		
		
		// now set up display
		minimized = false;
		
		
		// set params for layout manager
		GridBagLayout  theLayout = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		
		c.gridwidth = 1;
		c.gridheight = 1;
		c.fill = GridBagConstraints.NONE;
		c.ipadx = 0;
		c.ipady = 0;
		c.insets = new Insets(2,2,2,2);
		c.anchor = GridBagConstraints.CENTER;
		c.weightx = .5;
		c.weighty = .5;
		
		
		
		this.setTitle("AirPort Modem/PPPoE Utility");
		
		Panel buttonPanel = new Panel();
		buttonPanel.setLayout(theLayout);
		
		c.fill = GridBagConstraints.HORIZONTAL;
		
		c.gridx = 1;
		c.gridy = 1;
		theLayout.setConstraints(hangupModemButton, c);
		buttonPanel.add(hangupModemButton);
		
		c.gridx = 2;
		c.gridy = 1;
		theLayout.setConstraints(connectModemButton, c);
		buttonPanel.add(connectModemButton);
		
		
		c.fill = GridBagConstraints.NONE;
		
		
		Panel hostPanel = new Panel();
		hostPanel.setLayout(theLayout);
		
		c.gridx = 1;
		c.gridy = 1;
		theLayout.setConstraints(hostIDLabel, c);
		hostPanel.add(hostIDLabel);
		
		c.gridx = 2;
		c.gridy = 1;
		theLayout.setConstraints(hostIDField, c);
		hostPanel.add(hostIDField);
		
		
		c.gridx = 3;
		c.gridy = 1;
		theLayout.setConstraints(newHostButton, c);
		hostPanel.add(newHostButton);
		
		
		
		Panel modemStatusPanel = new Panel();
		modemStatusPanel.setLayout(theLayout);
		
		c.gridx = 1;
		c.gridy = 1;
		c.anchor = GridBagConstraints.EAST;
		theLayout.setConstraints(modemStatusLabel, c);
		modemStatusPanel.add(modemStatusLabel);
		
		c.gridx = 2;
		c.gridy = 1;
		c.anchor = GridBagConstraints.WEST;
		theLayout.setConstraints(modemStatusField, c);
		modemStatusPanel.add(modemStatusField);
		
		c.gridx = 1;
		c.gridy = 2;
		c.anchor = GridBagConstraints.EAST;
		theLayout.setConstraints(timeLabel, c);
		modemStatusPanel.add(timeLabel);
		
		c.gridx = 2;
		c.gridy = 2;
		c.anchor = GridBagConstraints.WEST;
		theLayout.setConstraints(timeField, c);
		modemStatusPanel.add(timeField);
		
		/*
		Panel modemStatusOuterPanel = new Panel();
		modemStatusOuterPanel.setLayout(theLayout);
		
		c.gridx = 1;
		c.gridy = 1;
		c.anchor = GridBagConstraints.CENTER;
		theLayout.setConstraints(modemStatusPanel, c);
		modemStatusOuterPanel.add(modemStatusPanel);
		
		c.gridx = 1;
		c.gridy = 2;
		theLayout.setConstraints(connectTimeCaveatLabel, c);
		modemStatusOuterPanel.add(connectTimeCaveatLabel);
		*/
		

		
		c.gridwidth = 1;
		c.anchor = GridBagConstraints.CENTER;
		
		
		
		
		this.getContentPane().setLayout(theLayout);
		
		
		c.gridx = 1;
		c.gridy = 1;
		theLayout.setConstraints(hostPanel, c);
		this.getContentPane().add(hostPanel);
		
		
		c.gridx = 1;
		c.gridy = 2;
		c.fill = GridBagConstraints.HORIZONTAL;
		theLayout.setConstraints(buttonPanel, c);
		this.getContentPane().add(buttonPanel);
		
		c.fill = GridBagConstraints.NONE;
		
		c.gridx = 1;
		c.gridy = 3;
		theLayout.setConstraints(modemStatusPanel, c);
		this.getContentPane().add(modemStatusPanel);
		
		/*
		c.gridx = 1;
		c.gridy = 4;
		JLabel messagesLabel = new JLabel("Messages:");
		theLayout.setConstraints(messagesLabel, c);
		this.getContentPane().add(messagesLabel);
		
		c.fill = GridBagConstraints.BOTH;
		c.gridx = 1;
		c.gridy = 5;
		theLayout.setConstraints(messagesScroll, c);
		this.getContentPane().add(messagesScroll);				
		*/
		
		/*
		c.gridx = 1;
		c.gridy = 6;
		theLayout.setConstraints(authorLabel, c);
		this.getContentPane().add(authorLabel);
		*/
		
		
		
	}
	
	
	
	// WindowListener methods
	
	public void windowActivated(WindowEvent e)
	{
		// do nothing
	}
	
	
	public void windowClosing(WindowEvent e)
	{
	    // exit
	    System.exit(0);
	}
	
	
	public void windowClosed(WindowEvent e)
	{
		// do nothing
	}
	
	
	public void windowDeactivated(WindowEvent e)
	{
		// do nothing
	}
	
	
	public void windowOpened(WindowEvent e)
	{
		// do nothing
	}
	
	
	public void windowIconified(WindowEvent e)
	{
	    // display minimized stuff; will print just connect time (or "Unconnected") as title text
	    minimized = true;
	    
	}
	
	
	public void windowDeiconified(WindowEvent e)
	{
	    // display full title; connect time will be placed in
	    minimized = false;
	    this.setTitle("AirPort Modem/PPPoE Utility");
	}
	
	
	
	
	
	public void actionPerformed(ActionEvent theEvent)
	// respond to button pushes, menu selections
	{
		String command = theEvent.getActionCommand();
		
	
		if (command == "quit")
		{
			System.exit(0);
		}
		
		
		
		if (command == "new host")
		{
			
			String newHost = JOptionPane.showInputDialog("Input new host:");
			if (newHost != null)
			{
				
				try
				{
					hostAddress = InetAddress.getByName(newHost);
					hostIDField.setText(newHost);
				
				}
				catch(UnknownHostException e)
				{
					JOptionPane.showMessageDialog(this, "Unknown host name supplied.");
				}
				catch(Exception e)
				{
					JOptionPane.showMessageDialog(this, "Error setting new host.");
				}
			}
			
		}
		
		
		
		if (command == "hangup modem")
		{
			hangupModem();
		}	
		
		
		
		if (command == "connect modem")
		{
			connectModem();
		}
		
		
	
		
	}
	
	
	
	private void hangupModem() 
	{
		try
		{
			messagesArea.setText("Hanging up modem....");
			
			DatagramSocket dSocket = new DatagramSocket();
			dSocket.setSoTimeout(5000);	// 5 seconds
			
			byte[] bytes = new byte[116];	// from sniffs
			bytes[0] = (byte)0x06;			// from S. Sexton - thanks!
			
			DatagramPacket outPacket = new DatagramPacket(bytes, bytes.length, hostAddress, OSU_NMS_PORT);
					
			dSocket.send(outPacket);
			
			
			/*
			// don't bother waiting for a reply
			DatagramPacket inPacket = new DatagramPacket(bytes, bytes.length);
			dSocket.receive(inPacket);
			bytes = inPacket.getData();
			*/
			
			/*
			System.out.println("Returned Message bytes:");
			for (int i = 0; i < bytes.length; ++i)
				System.out.print(hexByte(bytes[i]) + " ");
			*/
			
			/*
			int rows = 8;	// really, 7.25
			int cols = 16;
			ByteBlock block = new ByteBlock(rows, cols, bytes);
			AirportDiscoveryInfo theInfo = new AirportDiscoveryInfo(block);
			
			theArea.append("Reply received:\n");
			theArea.append("Device address: " + theInfo.get("Base station IP address").toString() + "\n");
			theArea.append("Device name:    " + theInfo.get("Base station name").toString() + "\n");
			theArea.append("Device type:    " + theInfo.get("Device identifying string").toString() + "\n");
			theArea.append("\n");
			*/
			
			messagesArea.append("please wait for modem to disconnect.\n");
			
			
				
					
		}
		catch(Exception e)
		{
			messagesArea.append("Exception during hangup:  " + e + "\n");
		}
		
	}
	
	
	
	private void connectModem() 
	{
		try
		{
			messagesArea.setText("Dialing modem....");
			
			DatagramSocket dSocket = new DatagramSocket();
			dSocket.setSoTimeout(5000);	// 5 seconds
			
			byte[] bytes = new byte[116];	// from sniffs
			bytes[0] = (byte)0x07;			// from P. Werz - thanks!
			
			
			DatagramPacket outPacket = new DatagramPacket(bytes, bytes.length, hostAddress, OSU_NMS_PORT);
					
			dSocket.send(outPacket);
			
			
			/*
			// don't bother waiting for a reply
			DatagramPacket inPacket = new DatagramPacket(bytes, bytes.length);
			dSocket.receive(inPacket);
			bytes = inPacket.getData();
			*/
			
			/*
			System.out.println("Returned Message bytes:");
			for (int i = 0; i < bytes.length; ++i)
				System.out.print(hexByte(bytes[i]) + " ");
			*/
			
			/*
			int rows = 8;	// really, 7.25
			int cols = 16;
			ByteBlock block = new ByteBlock(rows, cols, bytes);
			AirportDiscoveryInfo theInfo = new AirportDiscoveryInfo(block);
			
			theArea.append("Reply received:\n");
			theArea.append("Device address: " + theInfo.get("Base station IP address").toString() + "\n");
			theArea.append("Device name:    " + theInfo.get("Base station name").toString() + "\n");
			theArea.append("Device type:    " + theInfo.get("Device identifying string").toString() + "\n");
			theArea.append("\n");
			*/
			
			messagesArea.append("please wait for modem to connect.\n");
					
		}
		catch(Exception e)
		{
			messagesArea.append("Exception during modem connect:  " + e + "\n");
		}
		
	}
	
	
	
	
	
	private String hexByte(byte b)
	{
		int pos = b;
		if (pos < 0)
			pos += 256;
		String returnString = new String();
		returnString += Integer.toHexString(pos/16);
		returnString += Integer.toHexString(pos%16);
		return returnString;
	}
	
	
	
	
	public void run()
	{
		
		while(true)
		{
		
			try
			{
			
				// send request for state of modem: use 116-byte payload to keep version 1 base stations
				// happy; 0801 requests status info; 0310 requests all info at or following item number
				// 0310
				byte[] payloadBytes = new byte[116];
				payloadBytes[0] = (byte)0x08;
				payloadBytes[1] = (byte)0x01;
				payloadBytes[2] = (byte)0x03;
				payloadBytes[3] = (byte)0x10;
				
				DatagramPacket outPacket = new DatagramPacket(payloadBytes, payloadBytes.length, hostAddress, OSU_NMS_PORT);
						
				dSocket.send(outPacket);
				
				
				// wait for a reply; 128 bytes should be enough
				byte[] receivedBytes = new byte[128];	
				
				DatagramPacket inPacket = new DatagramPacket(receivedBytes, receivedBytes.length);
				dSocket.receive(inPacket);
				receivedBytes = inPacket.getData();
				int receivedLength = inPacket.getLength();
				
				// now parse the received bytes into a hash of info
				OSUNMSInfoHash infoHash = new OSUNMSInfoHash(receivedBytes, receivedLength);
				
				// test element number 0311: will be 4 if modem connected
				int connectedValue = infoHash.get(new Integer(0x0311)).getIntegerValue();
				
				switch (connectedValue)
				{
				
				
					case 4:
					{
						// connected
						hangupModemButton.setEnabled(true);
						connectModemButton.setEnabled(false);
						
						String statusString = "Connected";
						
						// get connect speed from element number 0315: only valid for version 2
						// base station, where length is 6; for version 1, value is always 115,200
						// and returned as hex string of digits!
						OSUNMSInfoElement speedElement = infoHash.get(new Integer(0x0315));
						if (speedElement.length == 6)
						{
							int speed = speedElement.getIntegerValue();
							if (speed > 0)
							{
								statusString += "  (" + speed + " bps)";
							}
						}
						
						modemStatusField.setText(statusString);
						
						// if connected, see for how long
						int connectionTime = infoHash.get(new Integer(0x0316)).getIntegerValue();
						
						// change to hours:minutes:seconds format
						int hours = connectionTime / 3600;
						int minutes = (connectionTime / 60) % 60;
						int seconds = connectionTime % 60;
						
						// make hours, minutes and seconds have 2 digits
						String hourString = new String();
						hourString += hours;
						if (hourString.length() < 2)
							hourString = "0" + hourString;
						
						String minuteString = new String();
						minuteString += minutes;
						if (minuteString.length() < 2)
							minuteString = "0" + minuteString;
						
						String secondString = new String();
						secondString += seconds;
						if (secondString.length() < 2)
							secondString = "0" + secondString;
						
						String timeString = hourString + ":" + minuteString + ":" + secondString;
						
						timeLabel.setText("Connection time:");
						timeField.setText(timeString);
						
						if (minimized)
							this.setTitle(timeString);
				
						break;
					}
					case 5:
					{
						// modem temporarily disabled
						modemStatusField.setText("Temporarily disabled");
						if (minimized)
							this.setTitle("Disabled");
						
						hangupModemButton.setEnabled(false);
						connectModemButton.setEnabled(true);
						
						// set time field to time remaining while disabled
						timeLabel.setText("Time remaining:");
						int remainingTime = infoHash.get(new Integer(0x0319)).getIntegerValue();
						String remainingTimeString = Integer.toString(remainingTime);
						if (remainingTimeString.length() < 2)
							remainingTimeString = "0" + remainingTimeString;
						timeField.setText("0:" + remainingTimeString);
						
						break;
					}
					
					case 2:
					case 3:
					{
						// modem/PPPoE connecting
						modemStatusField.setText("Connecting...");
						if (minimized)
							this.setTitle("Connecting...");
						
						hangupModemButton.setEnabled(true);
						connectModemButton.setEnabled(false);
						
						// make sure connect time field erased
						timeLabel.setText("Connection time:");
						timeField.setText("");
						
						break;
					}
					
					case 1:
					default:
					{
						// modem PPPoE disconnected (but not disabled)
						modemStatusField.setText("Unconnected");
						if (minimized)
							this.setTitle("Unconnected");
							
						hangupModemButton.setEnabled(false);
						connectModemButton.setEnabled(true);
						
						// make sure time field erased
						timeLabel.setText("Connection time:");
						timeField.setText("");
						
						break;
					}
						
				}
					
				//messagesArea.setText("Modem status checked " + (new Date()).toString() + ";\nStatus = " + connectedValue);
			
			}
			catch(InterruptedIOException e)
			{
				// don't bother informing of interruption
				messagesArea.setText("Exception during modem status polling:  " + e + "\n");
			}
			catch(Exception e)
			{
				messagesArea.setText("Exception during modem status polling:  " + e + "\n");
			}
			
			
			try
			{
				// sleep for 1 second
				Thread.sleep(1000);
			}
			catch(InterruptedException e)
			{
				// don't bother informing of interruption
				//messagesArea.setText("Exception during modem status polling:  " + e + "\n");
			}
			
		
		}
		
		
	}

	
	
	
	
	public static void main(String args[]) 
	{
		try
		{
			String defaultIPAddress = "10.0.1.1";
			
			if (args.length > 0)
			{
				defaultIPAddress = args[0];
			}
			
			AirportBaseStationHangup theApp = new AirportBaseStationHangup(defaultIPAddress);
			theApp.pack();
			theApp.show();
		}
		catch (Exception e)
		{
			System.out.println("Error on startup: " + e);
			System.exit(0);
		}
	}
	

}