/*
 * @(#)FileOutputStream.java
 *
 * Copyright (c) 2002-2003 JSCAPE
 * 1147 S. 53rd Pl., Mesa, Arizona, 85206, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * JSCAPE. ("Confidential Information").  You shall not disclose such
 * Confidential Information and shall use it only in accordance with
 * the terms of the license agreement you entered into with JSCAPE.
 */

/*
 * Classname: FileOutputStream
 *
 * Version: 1.0
 *
 * Author: Alex Usun
 */
package com.jscape.util.io;

import com.jscape.util.ExceptionTools;
import com.jscape.util.IOTools;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.nio.file.Path;
import java.nio.file.Paths;

import static com.jscape.util.Parameters.assertNotNull;

/**
 * The file output stream.
 *
 * @author Alex Usun
 */
public class FileOutputStream
        extends OutputStream {

    protected final RandomAccessFile base;

    public static FileOutputStream streamFor(File file, long offset, boolean truncate)
            throws IOException {
        RandomAccessFile base = new RandomAccessFile(file, "rw");

        try {
            base.seek(offset);

            if (truncate) {
                base.setLength(offset);
            }

            return new FileOutputStream(base);
        } catch (Exception e) {
            IOTools.close(base);
            throw ExceptionTools.ioException(e);
        }
    }

    public static FileOutputStream streamFor(Path file, long offset, boolean truncate)
            throws IOException {
        return streamFor(file.toFile(), offset, truncate);
    }

    public static FileOutputStream streamFor(String file, long offset, boolean truncate)
            throws IOException {
        return streamFor(Paths.get(file), offset, truncate);
    }

    public FileOutputStream(RandomAccessFile base) {
        assertNotNull(base);
        this.base = base;
    }

    public void close() {
        IOTools.close(this.base);
    }

    public void write(int data)
            throws IOException {
        this.base.write(data);
    }

    public void write(byte[] data, int offset, int length)
            throws IOException {
        this.base.write(data, offset, length);
    }

}
