/*
	A basic extension of the java.awt.Frame class
 */

import java.awt.*;
import JRTPMon;
import java.net.RTP.*;
import java.net.RTP.Packets.*;

public class frMain extends Frame 
{
    private static String IP;
    private static int Port;
    private static int PayloadType;
    
    private static Session rtpSession;
    private static frRTCPMonitor RTCPMon;
    private static frRTPMonitor RTPMon;
    
	public frMain( )
	{
		// This code is automatically generated by Visual Cafe when you add
		// components to the visual environment. It instantiates and initializes
		// the components. To modify the code, only use code syntax that matches
		// what Visual Cafe can generate, or Visual Cafe may be unable to back
		// parse your Java file into its visual environment.
		//{{INIT_CONTROLS
		setLayout(null);
		setVisible(false);
		setSize(insets().left + insets().right + 262,insets().top + insets().bottom + 166);
		txtAddress = new java.awt.TextField();
		txtAddress.setText("234.5.6.7/8000,4");
		txtAddress.setBounds(insets().left + 12,insets().top + 36,156,36);
		txtAddress.setBackground(new Color(16777215));
		add(txtAddress);
		label1 = new java.awt.Label("Multicast Group Address/port,Payloadtype");
		label1.setBounds(insets().left + 12,insets().top + 12,240,24);
		add(label1);
		cmdConnect = new java.awt.Button();
		cmdConnect.setLabel("Connect");
		cmdConnect.setBounds(insets().left + 168,insets().top + 36,84,24);
		cmdConnect.setBackground(new Color(12632256));
		add(cmdConnect);
		cmdShowRTCP = new java.awt.Button();
		cmdShowRTCP.setLabel("RTCP");
		cmdShowRTCP.setBounds(insets().left + 108,insets().top + 96,72,24);
		cmdShowRTCP.setBackground(new Color(12632256));
		add(cmdShowRTCP);
		cmdShowRTCP.setEnabled(false);
		cmdShowRTP = new java.awt.Button();
		cmdShowRTP.setLabel("RTP");
		cmdShowRTP.setBounds(insets().left + 12,insets().top + 96,72,24);
		cmdShowRTP.setBackground(new Color(12632256));
		add(cmdShowRTP);
		cmdShowRTP.setEnabled(false);
		label3 = new java.awt.Label("Show the following packets");
		label3.setBounds(insets().left + 12,insets().top + 72,165,23);
		add(label3);
		cmdExit = new java.awt.Button();
		cmdExit.setLabel("Exit");
		cmdExit.setBounds(insets().left + 180,insets().top + 132,72,24);
		cmdExit.setBackground(new Color(12632256));
		add(cmdExit);
		lblStatus = new java.awt.Label("");
		lblStatus.setBounds(insets().left + 12,insets().top + 132,165,23);
		add(lblStatus);
		setTitle("RTP Monitor");
		//}}

		//{{INIT_MENUS
		//}}

		//{{REGISTER_LISTENERS
		SymWindow aSymWindow = new SymWindow();
		this.addWindowListener(aSymWindow);
		SymAction lSymAction = new SymAction();
		cmdConnect.addActionListener(lSymAction);
		cmdExit.addActionListener(lSymAction);
		SymMouse aSymMouse = new SymMouse();
		cmdExit.addMouseListener(aSymMouse);
		cmdShowRTP.addActionListener(lSymAction);
		cmdShowRTCP.addActionListener(lSymAction);
		//}}
		
	}

	public frMain(String title)
	{
		this();
		setTitle(title);
		
	}

	public synchronized void show()
	{
		move(50, 50);
		super.show();
	}

	public void addNotify()
	{
	    // Record the size of the window prior to calling parents addNotify.
	    Dimension d = getSize();
	    
		super.addNotify();

		if (fComponentsAdjusted)
			return;

		// Adjust components according to the insets
		setSize(insets().left + insets().right + d.width, insets().top + insets().bottom + d.height);
		Component components[] = getComponents();
		for (int i = 0; i < components.length; i++)
		{
			Point p = components[i].getLocation();
			p.translate(insets().left, insets().top);
			components[i].setLocation(p);
		}
		fComponentsAdjusted = true;
	}

    // Used for addNotify check.
	boolean fComponentsAdjusted = false;

	//{{DECLARE_CONTROLS
	java.awt.TextField txtAddress;
	java.awt.Label label1;
	java.awt.Button cmdConnect;
	java.awt.Button cmdShowRTCP;
	java.awt.Button cmdShowRTP;
	java.awt.Label label3;
	java.awt.Button cmdExit;
	java.awt.Label lblStatus;
	//}}

	//{{DECLARE_MENUS
	//}}

	class SymWindow extends java.awt.event.WindowAdapter
	{
		public void windowClosing(java.awt.event.WindowEvent event)
		{
			Object object = event.getSource();
			if (object == frMain.this)
				Frame1_WindowClosing(event);
		}
	}
	
	void Frame1_WindowClosing(java.awt.event.WindowEvent event)
	{
		hide();		 // hide the Frame
	}

	class SymAction implements java.awt.event.ActionListener
	{
		public void actionPerformed(java.awt.event.ActionEvent event)
		{
			Object object = event.getSource();
			if (object == cmdConnect)
				cmdConnect_Action(event);
			else if (object == cmdExit)
				cmdExit_Action(event);
			else if (object == cmdShowRTP)
				cmdShowRTP_Action(event);
			else if (object == cmdShowRTCP)
				cmdShowRTCP_Action(event);
		}
	}

	void cmdConnect_Action(java.awt.event.ActionEvent event)
	{
	    // Toggle the connect disconnect button
        if ( cmdConnect.getLabel().equals( "Connect" ) ) {
            
            if ( this.ParseIPPort () > 0 ) {
                txtAddress.enable ( false );
                cmdConnect.setLabel ( "Disconnect" );
                this.StartSession ();
            }
            else 
                lblStatus.setText ( "Invalid IP/Port ");
        }
        else {
            txtAddress.enable ( true );
            cmdConnect.setLabel ( "Connect" );

            // Port is fine now, proceed with creating an RTPSession
            this.StopSession ();    
        }
	}

	void cmdExit_Action(java.awt.event.ActionEvent event)
	{
        // Disconnect from the Multicast group if connected
        
        // Exit the system
        // SYstem.
	}

	class SymMouse extends java.awt.event.MouseAdapter
	{
		public void mouseClicked(java.awt.event.MouseEvent event)
		{
			Object object = event.getSource();
			if (object == cmdExit)
				cmdExit_MouseClick(event);
		}
	}

	void cmdExit_MouseClick(java.awt.event.MouseEvent event)
	{
	    // Disconnect session 
	    // Send BYE Packet
	    
		JRTPMon.DestroyFrame();
	}
	
	private void StartSession () {
	    
	    lblStatus.setText ( "Connecting...");
	    
        rtpSession = new Session (  IP,             //  MulticastGroupIPAddress
                                    Port,           //  MulticastGroupPort
                                    Port+1,         //  RTCPGroupPort
                                    Port+5,         //  RTPSendFromPort
                                    Port+6,         //  RTCPSendFromPort
                                    10000           //  bandwidth
                                  );
        
        rtpSession.setPayloadType ( this.PayloadType );
        rtpSession.setCName ( "JRTPMon" );
        rtpSession.setEMail ( "monitor@ais.com" );
        rtpSession.DebugOutput = true;
        
        RTCPMon = new frRTCPMonitor ( rtpSession );
        RTPMon = new frRTPMonitor ( rtpSession );
        
        // Register the RTCP frame as the RTCP action listener
        Session.addRTCP_actionListener ( RTCPMon );
        Session.addRTP_actionListener ( RTPMon );
        
        // Start the receiver and sender threads
        rtpSession.StartRTCPSenderThread();
        rtpSession.StartRTCPReceiverThread();
        rtpSession.StartRTPReceiverThread();
        
        lblStatus.setText ( "Connected.");
        cmdShowRTP.enable ( true );
        cmdShowRTCP.enable ( true );
        
	}
	
	private void StopSession () {
	    
	    lblStatus.setText ( "Disconnecting..." );
	    
	    // Force a BYE packet by stopping the RTCP Sender thread
        rtpSession.StopRTCPSenderThread();
        
        cmdShowRTP.enable ( false );
        cmdShowRTCP.enable ( false );
	    lblStatus.setText ( "Disconnected." );

	}

	void cmdShowRTP_Action(java.awt.event.ActionEvent event)
	{
		// to do: code goes here.
			 
		//{{CONNECTION
		// show the Frame
		RTPMon.show();
		//}}
	}

	void cmdShowRTCP_Action(java.awt.event.ActionEvent event)
	{
		// to do: code goes here.
			 
		//{{CONNECTION
		// show the Frame
		RTCPMon.show();
		//}}
	}
	
	public int ParseIPPort ()
	{
        // Validate the internet address in the field and extract IP, Port and PayloadType 
        // from IP/Port,Payload formated input.
        // e.g. 234.5.6.7/8000,4
        String IPPortPayload = this.txtAddress.getText();
        
        int slashLocation = 0;
        int commaLocation = 0;
        
        if ( ( slashLocation = IPPortPayload.indexOf ( "/" ) ) == -1 ) {
            System.err.println ( " Slash character not found in the field: " + IPPortPayload );
            return -1;
        }
        
        if ( ( commaLocation = IPPortPayload.indexOf ( "," ) ) == -1 ) {
            System.err.println ( " comma delimiter not found in the field: " + IPPortPayload );
            return -1;
        }
        
        IP = IPPortPayload.substring ( 0, slashLocation );
        System.out.println ( "IP:" + IP );
        
        try {
            Port = Integer.parseInt ( IPPortPayload.substring ( slashLocation + 1 , commaLocation)  );
        }
        catch ( java.lang.NumberFormatException e )
        {
            System.err.println ( "Invalid Port number (must be an integer) " );
            return -1;
        }

        System.out.println ( "Port:" + Port );
        
        if ( Port > 36768 )
        {
            System.err.println ( "Port number larger than 36768" );
            return -1;
        }
        
        try {
            this.PayloadType = Integer.parseInt ( IPPortPayload.substring ( commaLocation + 1 )  );
        }
        catch ( java.lang.NumberFormatException e )
        {
            System.err.println ( "Invalid Payload Type (must be an integer) " );
            lblStatus.setText ( "Invalid Payload type");
            return -1;
        }
        System.out.println ( "PayloadType:" + PayloadType );
        
        return 1;
	}
}
