//go:build !js

package utils

import (
	
	
	
	
	
	
	

	
	
)

// DialWebSocket dials a WebSocket endpoint and returns a net.Conn carrying
// binary messages as a byte stream. Useful for tunneling stream protocols.
func (
	 context.Context,  string,  []string,  time.Duration,
) (net.Conn, error) {
	// ctx is honored by the dialer
	 := ws.Dialer{
		Protocols: ,
		Timeout:   ,
	}
	, , ,  := .Dial(, )
	if  != nil {
		return nil, 
	}

	return newWSConn(, , ws.StateClientSide), nil
}

// NewServerWSConn wraps an already upgraded server-side WebSocket into
// a net.Conn.
func (
	 net.Conn,  *bufio.ReadWriter,
) (net.Conn, error) {
	if  == nil ||  == nil {
		return nil, errors.New("ws conn required")
	}

	return newWSConn(, .Reader, ws.StateServerSide), nil
}

// wsConn adapts a WebSocket to net.Conn. Every Write becomes a single binary
// message; reads are exposed as a continuous byte stream.
type wsConn struct {
	conn net.Conn
	rd   *bufio.Reader
	side ws.State

	readMu  sync.Mutex
	writeMu sync.Mutex
	buf     []byte

	closeMu sync.Mutex
	closed  bool
}

var _ net.Conn = (*wsConn)(nil)

func newWSConn( net.Conn,  *bufio.Reader,  ws.State) *wsConn {
	if  == nil {
		 = bufio.NewReader()
	}

	return &wsConn{
		conn: ,
		rd:   ,
		side: ,
	}
}

func ( *wsConn) ( []byte) (int, error) {
	.readMu.Lock()
	defer .readMu.Unlock()

	for len(.buf) == 0 {
		var (
			 []byte
			  error
		)
		 := wsRW{r: .rd, w: .conn}
		if .side == ws.StateServerSide {
			, _,  = wsutil.ReadClientData()
		} else {
			, _,  = wsutil.ReadServerData()
		}
		if  != nil {
			return 0, mapWSErr()
		}
		.buf = 
	}

	 := copy(, .buf)
	.buf = .buf[:]

	return , nil
}

func ( *wsConn) ( []byte) (int, error) {
	.writeMu.Lock()
	defer .writeMu.Unlock()

	var  error
	if .side == ws.StateServerSide {
		 = wsutil.WriteServerMessage(.conn, ws.OpBinary, )
	} else {
		 = wsutil.WriteClientMessage(.conn, ws.OpBinary, )
	}
	if  != nil {
		return 0, mapWSErr()
	}

	return len(), nil
}

func ( *wsConn) () error {
	.closeMu.Lock()
	 := .closed
	.closed = true
	.closeMu.Unlock()

	if ! {
		// best-effort close frame
		 := ws.NewCloseFrame(ws.NewCloseFrameBody(
			ws.StatusNormalClosure, ""))
		if .side == ws.StateClientSide {
			 = ws.MaskFrameInPlace()
		}
		_ = ws.WriteFrame(.conn, )
	}

	return .conn.Close()
}

func ( *wsConn) () net.Addr {
	return .conn.LocalAddr()
}

func ( *wsConn) () net.Addr {
	return .conn.RemoteAddr()
}

func ( *wsConn) ( time.Time) error {
	return .conn.SetDeadline()
}

func ( *wsConn) ( time.Time) error {
	return .conn.SetReadDeadline()
}

func ( *wsConn) ( time.Time) error {
	return .conn.SetWriteDeadline()
}

// wsRW combines a buffered reader with a plain writer. Control frames are
// written directly to the underlying conn, so they are not stuck in a buffer.
type wsRW struct {
	r io.Reader
	w io.Writer
}

func ( wsRW) ( []byte) (int, error)  { return .r.Read() }
func ( wsRW) ( []byte) (int, error) { return .w.Write() }

func mapWSErr( error) error {
	var  wsutil.ClosedError
	if errors.As(, &) {
		return io.EOF
	}

	return 
}