package com.jscape.util.io;

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

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

/**
 * @author Alex Usun
 */
public class ComponentWritableFile<T>
        implements WritableFile<T> {

    private final DataSource source;
    private final DataWriter<T> writer;

    public ComponentWritableFile(DataSource source, DataWriter<T> writer) {
        assertNotNull(source);
        this.source = source;

        assertNotNull(writer);
        this.writer = writer;
    }

    @Override
    public boolean writeAllowed() {
        return this.source.writeAllowed();
    }

    @Override
    public void write(T data)
            throws IOException {
        try (OutputStream out = this.source.getOutputStream()) {
            this.writer.write(data, out);
        }
    }
}
