package livepage

import (
	
	
	
	
	
	
	

	
)

// WsMux multiplexes the binary frames of a page WebSocket into numbered
// streams. Text frames keep being handled by [Page]. Streams are created on
// demand with [WsMux.Open], also when a frame for an unknown stream arrives.
type WsMux struct {
	ctx context.Context
	ws  *websocket.Conn

	mu      sync.Mutex
	streams map[uint8]*wsStream
	closed  bool
}

// newWsMux creates a multiplexer for a single page WebSocket.
func newWsMux( context.Context,  *websocket.Conn) *WsMux {
	return &WsMux{
		ctx:     ,
		ws:      ,
		streams: map[uint8]*wsStream{},
	}
}

// Open returns the stream with the given id, creating it on demand. Streams
// are [net.Conn]s, so they can be used for protocols like aRPC.
func ( *WsMux) ( uint8) net.Conn {
	.mu.Lock()
	defer .mu.Unlock()

	if ,  := .streams[];  {
		return 
	}
	,  := io.Pipe()
	 := &wsStream{
		mux: ,
		id:  ,
		pr:  ,
		pw:  ,
	}
	.streams[] = 

	return 
}

// feed routes a single binary frame to its stream.
func ( *WsMux) ( []byte) {
	if len() == 0 {
		return
	}

	// stream 0 is the default for unframed data
	.Open([0]).(*wsStream).feed([1:])
}

func ( *WsMux) ( uint8,  []byte) (int, error) {
	 := make([]byte, len()+1)
	[0] = 
	copy([1:], )

	if  := .ws.Write(.ctx, websocket.MessageBinary, );  != nil {
		return 0, 
	}

	return len(), nil
}

// close tears down all the streams. It doesn't close the page WebSocket.
func ( *WsMux) () {
	.mu.Lock()
	if .closed {
		.mu.Unlock()
		return
	}
	.closed = true
	 := make([]*wsStream, 0, len(.streams))
	for ,  := range .streams {
		 = append(, )
	}
	.mu.Unlock()

	for ,  := range  {
		_ = .Close()
	}
}

// ///// ///// /////

// ///// STREAM

// ///// ///// /////

// wsStream is a single stream of a [WsMux], implementing [net.Conn].
type wsStream struct {
	mux *WsMux
	id  uint8

	pr *io.PipeReader
	pw *io.PipeWriter

	closed    atomic.Bool
	closeOnce sync.Once

	mu         sync.Mutex
	err        error
	readTimer  *time.Timer
	writeTimer *time.Timer
}

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

// feed pushes a frame into the stream. It blocks until the reader consumes it,
// providing backpressure to the page read loop.
func ( *wsStream) ( []byte) {
	if .closed.Load() {
		return
	}
	_, _ = .pw.Write()
}

func ( *wsStream) ( []byte) (int, error) {
	.mu.Lock()
	 := .err
	.mu.Unlock()
	if  != nil {
		return 0, 
	}
	if .closed.Load() {
		return 0, io.EOF
	}

	,  := .pr.Read()
	if  != nil {
		.mu.Lock()
		if .err != nil {
			 = .err
		}
		.mu.Unlock()
	}

	return , 
}

func ( *wsStream) ( []byte) (int, error) {
	if .closed.Load() {
		return 0, io.ErrClosedPipe
	}

	return .mux.send(.id, )
}

func ( *wsStream) () error {
	.closeOnce.Do(func() {
		.closed.Store(true)
		_ = .pw.CloseWithError(io.EOF)
		_ = .pr.CloseWithError(io.EOF)

		.mu.Lock()
		if .readTimer != nil {
			.readTimer.Stop()
			.readTimer = nil
		}
		if .writeTimer != nil {
			.writeTimer.Stop()
			.writeTimer = nil
		}
		.mu.Unlock()
	})

	return nil
}

func ( *wsStream) () net.Addr                { return wsMuxAddr{} }
func ( *wsStream) () net.Addr               { return wsMuxAddr{} }
func ( *wsStream) ( time.Time) error      { return .setDeadline(, true, true) }
func ( *wsStream) ( time.Time) error  { return .setDeadline(, true, false) }
func ( *wsStream) ( time.Time) error { return .setDeadline(, false, true) }

func ( *wsStream) ( time.Time, ,  bool) error {
	.mu.Lock()
	defer .mu.Unlock()

	 := func( **time.Timer) {
		if * != nil {
			(*).Stop()
			* = nil
		}
		if .IsZero() {
			return
		}

		 := time.Until()
		if  < 0 {
			 = 0
		}
		* = time.AfterFunc(, func() {
			.fail(os.ErrDeadlineExceeded)
		})
	}
	if  {
		(&.readTimer)
	}
	if  {
		(&.writeTimer)
	}

	return nil
}

func ( *wsStream) ( error) {
	.mu.Lock()
	if .err == nil {
		.err = 
	}
	.mu.Unlock()
	_ = .Close()
}

type wsMuxAddr struct{}

func (wsMuxAddr) () string { return "livepage" }
func (wsMuxAddr) () string  { return "livepage" }