/**
 * A RemoteTarget merely represents a consumer which is on a different host.
 * Given that RemoteTarget is a local object, it is sending data over the network.
 * 
 * E.g. you have a local TV card and a player on a different host,
 * then the local TV card (which is a Source here) would be a connected
 * to a RemoteTarget.
 * 
 * RemoteTarget is implemented as (part of) a HTTP server.
 */

package org.bucksch.zeipis.store;
import org.bucksch.zeipis.all.Util;
import org.bucksch.zeipis.core.CoreServer;
import org.bucksch.httpserver.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class RemoteTarget implements Target, HTTPHandler
{
  public RemoteTarget()
  {
    myID = ++myLastID;
    CoreServer.me.dispatchingServer().registerHandler(this, myURLPrefix + myID);
  }
  public void handle(HTTPRequest request)
    throws HTTPException, IOException
  {
    request.sendResponseHeaders(200, false);
    myStream = request.getResponseBody();
    CoreServer.me.dispatchingServer().unregisterHandler(myURLPrefix + myID);
    myConnectedCallback.run(); // can block
  }
  public URL url()
  {
    try {
      return new URL(CoreServer.me.baseURLForHost(Util.thisHostname()), myURLPrefix + myID);
    } catch (MalformedURLException e) { throw new RuntimeException(e); }
  }
  public void setConnectedCallback(Runnable callback)
  {
    myConnectedCallback = callback;
  }

  /**
   * TODO Can only be called when the remote part connected
   */
  public OutputStream outStream()
  {
    Util.debug("outstream requested from " + toString());
    return myStream;
  }

  // Data
  protected OutputStream myStream = null;
  protected Runnable myConnectedCallback = null;
  protected int myID = 0;
  static protected int myLastID = 0;
  
  // Config (unchangable)
  static protected String myURLPrefix = "stream/";
}
