package profilesj2me;

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

class J2MEBasicServiceSender extends Thread {
  J2MEBasicService basicService;
  TextMessage message;

  public J2MEBasicServiceSender(J2MEBasicService bs, TextMessage msg) {
    basicService = bs;
    message = msg;
  }

  public void run() {
    String id = (String) message.getRoute().elementAt(0);
    String url = null;
    message.getRoute().removeElementAt(0);

    // Recupera l'indirizzo
    J2MEDevice device = (J2MEDevice) basicService.getDevice(id);

    if (device == null) {
      System.out.println("Ind. non trovato... messaggio non iviato!");
      return;
    }
    url = device.getURL();

    byte[] data = message.toString().getBytes();

    L2CAPConnection con = null;
    int index = 0;
    byte[] temp = null;

    try {
      /*
       * Create a connection to the server
       */
      System.out.println("oki " + this.message);
      con = (L2CAPConnection) Connector.open(url, Connector.WRITE, true);
      System.out.println("doki " + this.message);
      /*
       * Determine the maximum amount of data I can send to the server.
       */
      int MaxOutBufSize = con.getTransmitMTU();
      temp = new byte[MaxOutBufSize];

      /*
       * Send as many packets as are needed to send the data
       */

      while (index < data.length) {

        /*
         * Determine if this is the last packet to send or if there
         * will be additional packets
         */
        if ( (data.length - index) < MaxOutBufSize) {
          temp = new byte[data.length - index];
          System.arraycopy(data, index, temp, 0, data.length - index);
        }
        else {
          temp = new byte[MaxOutBufSize];
          System.arraycopy(data, index, temp, 0, MaxOutBufSize);
        }

        con.send(temp);

        index += MaxOutBufSize;
      }


    }
    catch (BluetoothConnectionException e) {
      System.out.println("Failed to print message");
      System.out.println("\tBluetoothConnectionException: " + e.getMessage());
      System.out.println("\tStatus: " + e.getStatus());
    }
    catch (IOException e) {
      System.out.println("Failed to print message");
      System.out.println("\tIOException: " + e.getMessage());
    }
    finally {
      try {
        if (con != null)
        con.close();
      }
      catch (IOException ex) {
        ex.printStackTrace();
      }
    }

  }
}