import java.io.*;
import java.net.*;
import java.util.*;



/**
 * A communications link with an SFP host
 *
 * @version 1.0
 * @author  Prof. David Bernstein, James Madison University
 */
public class SFPConnection extends URLConnection
{
    private SFPSocket       s;

    public static final int DEFAULT_PORT = 5190;

    public static final int SIGNON       = 1;
    public static final int DATA         = 2;

    protected static final byte[] sfpon = 
     {(byte)'S',(byte)'F',(byte)'P',(byte)'O',
     (byte)'N',(byte)'\r',(byte)'\n',(byte)'\r',
     (byte)'\n'};


    /**
     * Construct a new SFPConnection
     *
     * @param u   The SFP URL of the host
     */
    public SFPConnection(URL u)
    {
       super(u);
    }

    /**
     * Connect with the SFP server
     */
    public synchronized void connect() throws IOException
    {
       int            port;
       String         host;

       if (!connected) 
       {
          port = url.getPort();
          if (port < 0) port = DEFAULT_PORT;
          host = url.getHost();

          s = new SFPSocket(host, port);

          connected = true;
       }
    }

    /**
     * Gets the content-type for this SFPConnection 
     *
     */
    public String getContentType()
    {
       return "binary/sfp";
    }

    /**
     * Get an InputStream for this SFPConnection 
     *
     * Note: This function will connect first if necessary
     */
    public synchronized InputStream getInputStream() throws IOException
    {
       if (!connected) connect();
       return s.getInputStream();
    }

    /**
     * Get an OutputStream for this SFPConnection 
     *
     * Note: This function will connect first if necessary
     */
    public synchronized OutputStream getOutputStream() throws IOException
    {
       if (!connected) connect();
       return s.getOutputStream();
    }
}
