package net.benhui.btgallery.spp_bt;

import java.io.*;
import javax.bluetooth.*;
import javax.microedition.io.*;

import net.benhui.btgallery.spp_gui.*;

/**
 *
 * <p>Title: Example Serial Port Profile Client</p>
 * Description: Important area: send_SPP_message()
 * This client only does the portion that send and receive data over a SPP
 * connection. In an actual client applicaion, you also need to do device
 * discovery and service discovery. This is taken care by Bluelet.
 * @author Ben Hui (www.benhui.net)
 * @version 1.0
 *
 * LICENSE:
 * This code is licensed under GPL. (See http://www.gnu.org/copyleft/gpl.html)
 */

public class SPP_Client
{

  public SPP_Client()
  {
  }


  /**
   * Send a message to server using Serial Port Profile.
   * Connect to incoming service record, send a text, and read
   * in a text. This method illustrate how to send and receive
   * data using serial port profile.
   * Device and service discovery is part of Serial Port client but it is
   * done by Bluelet component. See SPP_MIDlet for usage of Bluelet.
   * @param msg
   */
  public void send_SPP_message(ServiceRecord r, String msg)
  {
    boolean flag = true;
    log( "send_SPP2");
    // obtain the URL reference to this service on remote device
    String url  = r.getConnectionURL(ServiceRecord.NOAUTHENTICATE_NOENCRYPT, false );
    log("url:"+url);

    try
    {
      // obtain connection and stream to this service
      log("connected to server.");
	   msg=String.valueOf(1);
		// now the server should have echo back the string, so we read it
      // using input stream
      StreamConnection con = (StreamConnection) Connector.open( url );
      DataInputStream in = con.openDataInputStream();
		DataOutputStream out = con.openDataOutputStream();

	 while(flag) {
	   log("Sending '" +msg+ "'"); 
 
      // write data into serial stream
      out.writeUTF( msg );
      out.flush();

      // this wait is artificial, the purpose to do wait until the
      // server side really receive the message before we close the connection
      // in theory, this is not necessary, but when I use the Rococo simulator,
      // sometimes the connection dropped on the server side when I close it here
      // it may be a bug in Rococo simulator.
      Thread.sleep(1000);

      // finish, close output stream

      
      String s = in.readUTF();

      log("Reciving '"+s+"'");
		int i = Integer.parseInt(s);
		i = i + 1;
		msg=String.valueOf(i);

    }
      out.close();
      con.close();
    } catch (Exception e)
    {
      e.printStackTrace();
      SPP_MIDlet.alert( e, SPP_MIDlet.instance.spp_screen );
    }

  }

  public void log( String s )
  {
    SPP_MIDlet.log( s );
  }

}
