package testsupport

import (
	"context"
	"io"
)

type InmemoryConnection struct {
	ctx         context.Context
	frontToBack chan ([]byte)
	backToFront chan ([]byte)
	addr        string
}

func NewInmemoryConnection(ctx context.Context, addr string, channelSize int) *InmemoryConnection {
	pipe := InmemoryConnection{
		ctx: ctx,
		// TODO: somehow does not work with unbuffered channel and yamux
		frontToBack: make(chan []byte, channelSize),
		backToFront: make(chan []byte, channelSize),
		addr:        addr,
	}
	return &pipe
}

func (bitpipe *InmemoryConnection) Front() *ChannelReadWriteCloser {
	return pipe(bitpipe.ctx, bitpipe.backToFront, bitpipe.frontToBack, bitpipe.addr)
}

func (bitpipe *InmemoryConnection) Back() *ChannelReadWriteCloser {
	return pipe(bitpipe.ctx, bitpipe.frontToBack, bitpipe.backToFront, bitpipe.addr)
}

func pipe(ctx context.Context, receiveBuffer <-chan []byte, sendBuffer chan<- []byte, remoteAddr string) *ChannelReadWriteCloser {
	return NewChannelReadWriteCloser(ctx, receiveBuffer, sendBuffer)
}

func CreatePipe(ctx context.Context) (io.ReadWriteCloser, io.ReadWriteCloser) {
	bitpipe := NewInmemoryConnection(ctx, "inmemory", 10)
	return bitpipe.Front(), bitpipe.Back()
}