package com.jscape.inet.ftp;

import com.jscape.util.IOTools;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Special OutputStream implementation
 *
 * @author Alvaro
 */
public class FtpOutputStream
        extends OutputStream {

    /**
     * If it is true then allows to disconnect the ftp connection
     */
    private boolean close;
    /**
     * It is the internal OutputStream
     */
    private OutputStream out;
    /**
     * Current Ftp instance
     */
    private Ftp ftp;

    /**
     * Creates a new FtpOutputStream instance and keeps the ftp connection open
     *
     * @param ftp      Current ftp instance
     * @param connect  <code>true</code> to establish a ftp connection,
     *                 <code>false</code> otherwise
     * @param close    <code>true</code> to disconnect the ftp connection,
     *                 <code>false</code> otherwise
     * @param fileName The file name which is going to be used to create the ouputstream
     * @param pos      The offset
     * @param append   It is the append flag
     *
     * @throws FtpException
     * @throws IOException
     */
    public FtpOutputStream(Ftp ftp, boolean connect, boolean close,
                           String fileName, long pos, boolean append)
            throws FtpException, IOException {

        this.ftp = ftp;
        this.close = close;
        if (connect) {
            this.ftp.connect();

        }

        out = ftp.getOutputStream(fileName, pos, append);
    }

    /**
     * Method close
     * If close is true then it disconnect the ftp connection,
     * and reads the last response from the server
     *
     * @see java.io.OutputStream#close()
     */
    public void close() {
        IOTools.close(this.out);
        if (this.close) {
            this.ftp.disconnect();
        }
    }

    /**
     * Method flush
     * It invokes to the flush method of the internal OutputStream instance
     *
     * @see java.io.OutputStream#flush()
     */
    public void flush()
            throws IOException {
        out.flush();
    }

    /**
     * Method write
     * It invokes to the write method of the internal OutputStream instance
     *
     * @see java.io.OutputStream#write(byte[])
     */
    public void write(byte[] b)
            throws IOException {
        out.write(b);
    }

    /**
     * Method write
     * It invokes to the write method of the internal OutputStream instance
     *
     * @see java.io.OutputStream#write(byte[], int, int)
     */
    public void write(byte[] b, int off, int len)
            throws IOException {
        out.write(b, off, len);
    }

    /**
     * Method write
     * It invokes to the write method of the internal OutputStream instance
     *
     * @see java.io.OutputStream#write(int)
     */
    public void write(int b)
            throws IOException {
        out.write(b);
    }


}
