/**
 * Starts a recording on a remote host
 * 
 */

package org.bucksch.zeipis.recorder;
import org.bucksch.zeipis.all.*;
import org.bucksch.zeipis.core.CoreServer;
import java.io.*;
import java.net.*;
import java.sql.SQLException;

public class RemoteTVRecorder extends TVRecorder
{
  public RemoteTVRecorder(TVCard card)
    throws Misconfiguration, SQLException
  {
    super();
    if (card.isLocal())
      throw new Misconfiguration("This is a local TV card");
    myCard = card;
  }
  // XXX blocks. is it OK?
  public void startRecording(TVChannel tvchannel)
    throws Misconfiguration, CantUseTVCard
  {
    Util.debug("RemoteTVRecorder.startRecording");
    try {
      URL recorderURL;
      try {
        recorderURL = new URL(CoreServer.me.baseURLForHost(myCard.host()), "/device/start/" + myCard.id());
      } catch (MalformedURLException e) { throw new RuntimeException(e); }
      URLConnection conn = recorderURL.openConnection();
      conn.setRequestProperty("channel-id", tvchannel.id() + "");
      conn.setRequestProperty("target-caller", "true");  // XXX how to know local vs. remote target?
      Util.debug("connecting to " + recorderURL.toString());
      // TODO blocks
      conn.connect();
      myInStream = conn.getInputStream();
      Util.debug("connected");
    } catch (Exception e) {
      throw new CantUseTVCard("Starting the recording on remote TV card failed", e);
     }
  }
  public void stopRecording()
    throws CantUseTVCard
  {
    Util.debug("RemoteTVRecorder.stopRecording");
    try {
      inStream().close(); // TODO closes network connection?
    } catch (Exception e) { throw new CantUseTVCard("Sending command to remote TV card failed", e); }
  }

  public InputStream inStream()
    throws Exception
  {
    if (myInStream == null)
      throw new Exception("Recording not started yet. Call startRecording() before inStream()");
    return myInStream;
  }
  
  protected TVCard myCard;
  protected InputStream myInStream = null;
}
