/* BlinkenSim
 * version 0.1 date 2006-07-28
 * Copyright (C) 2004-2006: Stefan Schuermans <1stein@schuermans.info>
 * Copyleft: GNU public license - http://www.gnu.org/copyleft/gpl.html
 * a blinkenarea.org project
 */

package org.blinkenarea.BlinkenSim;

import java.lang.*;
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import org.blinkenarea.BlinkenSim.*;

public class DynMcufClient extends DataSource
{
  private InetAddress host;
  private int port;
  private DatagramSocket sock = null;
  private DynMcufClientSend send = null;
  private DynMcufClientRecv recv = null;

  public DynMcufClient( Applet applet )
  {
    String hostname = applet.getParameter( "host" );
    if( hostname == null || hostname.length( ) <= 0 )
      hostname = "proxy.blinkenlights.de";
    try
    {
      host = InetAddress.getByName( hostname );
    }
    catch( UnknownHostException e )
    {
      host = null;
    }

    String portStr = applet.getParameter( "port" );
    if( portStr != null )
      port = Integer.parseInt( portStr );
    if( port <= 0 || port > 65535 )
      port = 4242;
  }

  public void start( FrameReceiver receiver )
  {
    stop( );
    if( host == null || port == 0 )
      return;
    try
    {
      sock = new DatagramSocket( );
      send = new DynMcufClientSend( sock, host, port );
      recv = new DynMcufClientRecv( sock, host, port, receiver );
      recv.start( );
      send.start( );
    }
    catch( SocketException e )
    {
      sock = null;
      host = null;
      port = 0;
    }
  }

  public void stop( )
  {
    sock = null;
    if( send != null )
    {
      send.terminate( );
      send = null;
    }
    if( recv != null )
    {
      recv.terminate( );
      recv = null;
    }
  }
}
