package com.atlassian.bitbucket.mesh.sidecar;

import javax.annotation.Nonnull;
import java.io.PrintWriter;

import static java.util.Objects.requireNonNull;

/**
 * A {@link SidecarChannel} which uses a provided {@link PrintWriter} (like {@code System.out}) to send messages.
 */
public class WriterSidecarChannel implements SidecarChannel {

    private final PrintWriter writer;

    public WriterSidecarChannel(PrintWriter writer) {
        this.writer = writer;
    }

    @Override
    public void send(@Nonnull String message) {
        writer.print(requireNonNull(message, "message"));
        writer.print('\n'); //Don't use println; we always want LFs
        writer.flush(); //Flush to ensure the PrintWriter doesn't buffer the message
    }

    @Override
    public void send(@Nonnull String key, @Nonnull String value) {
        send(requireNonNull(key, "key") + ": " + requireNonNull(value, "value"));
    }
}
