package tcelllivepage

import (
	

	
	lp 
)

const (
	typeKey    = "tcell-key"
	typeMouse  = "tcell-mouse"
	typeWheel  = "tcell-wheel"
	typeResize = "tcell-resize"
)

// domInput is the JSON envelope sent in [lp.DomEvent.Data].
type domInput struct {
	Key    string `json:"key"`
	Code   string `json:"code"`
	Action string `json:"action"`
	Repeat bool   `json:"repeat"`

	X       int     `json:"x"`
	Y       int     `json:"y"`
	Button  int     `json:"button"`
	Buttons int     `json:"buttons"`
	DeltaX  float64 `json:"deltaX"`
	DeltaY  float64 `json:"deltaY"`
	Cols    int     `json:"cols"`
	Rows    int     `json:"rows"`

	Ctrl  bool `json:"ctrl"`
	Alt   bool `json:"alt"`
	Shift bool `json:"shift"`
	Meta  bool `json:"meta"`
}

func ( *domInput) () tcell.ModMask {
	var  tcell.ModMask
	if .Shift {
		 |= tcell.ModShift
	}
	if .Ctrl {
		 |= tcell.ModCtrl
	}
	if .Alt {
		 |= tcell.ModAlt
	}
	if .Meta {
		 |= tcell.ModMeta
	}
	return 
}

// handleEvent routes a livepage DOM event to the screen.
func ( *Screen) ( *lp.DomEvent) {
	if  == nil {
		return
	}
	var  domInput
	if .Data != "" {
		if  := json.Unmarshal([]byte(.Data), &);  != nil {
			return
		}
	}

	switch .Type {
	case typeKey:
		.injectKey(&)
	case typeMouse:
		.injectMouse(&)
	case typeWheel:
		.injectWheel(&)
	case typeResize:
		// Multiple browser clients share one grid: use the smallest viewport.
		if .Client != "" {
			.resizeClient(.Client, .Cols, .Rows)
			return
		}
		if !.ResizeGrid(.Cols, .Rows) {
			// A client connected with the same viewport size. Rendering may
			// have been skipped while offline, so force a fresh frame for the
			// dispatch which follows this event.
			.forceFrame()
		}
	}
}

// resizeClient stores the viewport of a browser client and resizes the grid to
// the smallest viewport among all clients.
func ( *Screen) ( string, ,  int) {
	if  <= 0 ||  <= 0 ||  > maxDim ||  > maxDim {
		return
	}

	.sizesMx.Lock()
	.sizes[] = [2]int{, }
	, , _ = minSize(.sizes)
	.sizesMx.Unlock()

	if !.ResizeGrid(, ) {
		// The smallest viewport did not change, but the new client needs a
		// frame for the dispatch which follows its resize event.
		.forceFrame()
	}
}

// handleClient drops a disconnected client's viewport and resizes the grid to
// the smallest of the remaining clients.
func ( *Screen) ( string,  bool) {
	if  {
		return
	}

	.sizesMx.Lock()
	delete(.sizes, )
	, ,  := minSize(.sizes)
	.sizesMx.Unlock()
	if ! {
		return
	}

	if !.ResizeGrid(, ) {
		.forceFrame()
	}
}

// minSize returns the smallest viewport among all clients.
func minSize( map[string][2]int) (int, int, bool) {
	var (
		,  int
		      bool
	)
	for ,  := range  {
		if ! {
			, ,  = [0], [1], true
			continue
		}
		 = min(, [0])
		 = min(, [1])
	}

	return , , 
}

// forceFrame renders a fresh frame for the next livepage dispatch, even when
// the grid did not change.
func ( *Screen) () {
	.mu.Lock()
	.dirty = true
	.gen++
	.mu.Unlock()
	.renderNow()
}

func ( *Screen) ( *domInput) {
	, ,  := mapKey()
	if ! {
		return
	}
	// NewEventKey normalizes Ctrl+letter and Shift+Tab.
	_ = .PostEvent(tcell.NewEventKey(, , .modMask()))
}

func ( *Screen) ( *domInput) {
	var  tcell.ButtonMask
	switch .Action {
	case "down", "up", "move":
		 = browserButtons(.Buttons)
		if .Action == "down" &&  == 0 {
			 = browserButton(.Button)
		}
	default:
		return
	}

	,  := .clampCell(.X, .Y)
	_ = .PostEvent(tcell.NewEventMouse(, , , .modMask()))
}

func ( *Screen) ( *domInput) {
	var  tcell.ButtonMask
	if .DeltaY < 0 {
		 |= tcell.WheelUp
	} else if .DeltaY > 0 {
		 |= tcell.WheelDown
	}
	if .DeltaX < 0 {
		 |= tcell.WheelLeft
	} else if .DeltaX > 0 {
		 |= tcell.WheelRight
	}
	if  == 0 {
		return
	}

	,  := .clampCell(.X, .Y)
	_ = .PostEvent(tcell.NewEventMouse(, , , .modMask()))
}

func ( *Screen) (,  int) (int, int) {
	,  := .Size()
	if  <= 0 ||  <= 0 {
		return 0, 0
	}
	if  < 0 {
		 = 0
	} else if  >=  {
		 =  - 1
	}
	if  < 0 {
		 = 0
	} else if  >=  {
		 =  - 1
	}
	return , 
}

// browserButton converts a DOM MouseEvent.button value to a tcell button.
func browserButton( int) tcell.ButtonMask {
	switch  {
	case 0:
		return tcell.Button1 // left
	case 1:
		return tcell.Button3 // middle
	case 2:
		return tcell.Button2 // right
	}
	return tcell.ButtonNone
}

// browserButtons converts a DOM MouseEvent.buttons bitmask to a tcell mask.
func browserButtons( int) tcell.ButtonMask {
	var  tcell.ButtonMask
	if &1 != 0 {
		 |= tcell.Button1 // left
	}
	if &2 != 0 {
		 |= tcell.Button2 // right
	}
	if &4 != 0 {
		 |= tcell.Button3 // middle
	}
	return 
}

var namedKeys = map[string]tcell.Key{
	"Enter":      tcell.KeyEnter,
	"Tab":        tcell.KeyTab,
	"Backspace":  tcell.KeyBackspace,
	"Delete":     tcell.KeyDelete,
	"Insert":     tcell.KeyInsert,
	"Escape":     tcell.KeyEscape,
	"Esc":        tcell.KeyEscape,
	"ArrowUp":    tcell.KeyUp,
	"ArrowDown":  tcell.KeyDown,
	"ArrowLeft":  tcell.KeyLeft,
	"ArrowRight": tcell.KeyRight,
	"Home":       tcell.KeyHome,
	"End":        tcell.KeyEnd,
	"PageUp":     tcell.KeyPgUp,
	"PageDown":   tcell.KeyPgDn,
	"F1":         tcell.KeyF1,
	"F2":         tcell.KeyF2,
	"F3":         tcell.KeyF3,
	"F4":         tcell.KeyF4,
	"F5":         tcell.KeyF5,
	"F6":         tcell.KeyF6,
	"F7":         tcell.KeyF7,
	"F8":         tcell.KeyF8,
	"F9":         tcell.KeyF9,
	"F10":        tcell.KeyF10,
	"F11":        tcell.KeyF11,
	"F12":        tcell.KeyF12,
}

// mapKey converts a DOM key to a tcell key and rune.
func mapKey( *domInput) (tcell.Key, rune, bool) {
	if ,  := namedKeys[.Key];  {
		return , 0, true
	}
	if .Key == " " || .Key == "Spacebar" {
		return tcell.KeyRune, ' ', true
	}
	if  := []rune(.Key); len() == 1 {
		return tcell.KeyRune, [0], true
	}
	return 0, 0, false
}