package me.proxylink.plugin.tunnel;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.concurrent.atomic.AtomicBoolean;

final class LocalStream {
    private final long streamId;
    private final Socket socket;
    private final OutputStream output;
    private final AtomicBoolean closed = new AtomicBoolean(false);

    LocalStream(long streamId, Socket socket) throws IOException {
        this.streamId = streamId;
        this.socket = socket;
        this.output = socket.getOutputStream();
    }

    long streamId() {
        return streamId;
    }

    Socket socket() {
        return socket;
    }

    boolean markClosed() {
        return closed.compareAndSet(false, true);
    }

    boolean isClosed() {
        return closed.get();
    }

    void write(byte[] payload) throws IOException {
        synchronized (output) {
            output.write(payload);
            output.flush();
        }
    }

    void closeSocket() {
        try {
            socket.close();
        } catch (IOException ignored) {
        }
    }
}
