package org.bucksch.zeipis.recorder;
import org.bucksch.zeipis.all.Util;

public class DVBCANativeLinuxZap implements DVBCA
{
  static {
    System.loadLibrary("zeipisdvbca"); // TODO catch and recover when not loadable
  }
  public void start(final DVBCard card, final DVBChannel channel)
    throws CantUseTVCard
  {
    if (card.myDeviceNumber < 0 || card.myDeviceNumber > 9)
       throw new CantUseTVCard("DVB adapter number " + card.myDeviceNumber + " is wrong"); // TODO Misconfiguration()
    Util.debug("Starting CA for DVB card " + card.id() + ", service id " + channel.serviceID);
    myJavaThread = new Thread() {
      public void run()
      {
        try {
          Util.debug("java thread started");
          myCppThread = ++myLastCppThread;
          caStart(card.myDeviceNumber, channel.serviceID, myCppThread);
          Util.debug("java got thread# " + myCppThread);
        } catch (CantUseTVCard e) { Util.error(e); } // TODO report properly
      }
    };
    myJavaThread.start();
  }
  public void stop()
    throws CantUseTVCard
  {
    Util.debug("java closes thread# " + myCppThread);
    if (myCppThread >= 0)
      caStop(myCppThread);
//    try {
//      myJavaThread.join(2000);
//    } catch (InterruptedException e) { Util.debug("CA Java thread did not die (within 2s)"); }
  }
  protected native void caStart(int adapterNo, int channelServiceID, long handle)
    throws CantUseTVCard;
  protected native void caStop(long threadID)
    throws CantUseTVCard;
  
  // Data
  protected long myCppThread = -1;
  static protected long myLastCppThread = 0;
  protected Thread myJavaThread = null;
}
