package debugger

import (
	
	
	
	
	
	

	
	
	

	

	amhelp 
	am 
)

// regexp removing [foo]
var re = regexp.MustCompile(`\[(.*?)\]`)

// TODO move
func normalizeText( string) string {
	return strings.ToLower(re.ReplaceAllString(, ""))
}

func ( *Debugger) () {
	 := .hInitFocusManager()

	// custom keys
	for ,  := range .getKeystrokes() {
		 := .Set(, )
		if  != nil {
			log.Printf("Error: binding keys %s", )
		}
	}

	.hSearchSchemaClients()

	// Draw only the affected components: am-dbg handlers/states redraw their
	// changes, and app-level keys redraw the focused primitive instead of the
	// whole screen (which repaints unrelated layers).
	.App.SetDrawOnKey(false)
	.App.SetInputCapture(func( *tcell.EventKey) *tcell.EventKey {
		// the schema filter accepts all keys except focus cycling and quit
		var  *tcell.EventKey
		 := .App.GetFocus() == .treeFilterOut
		if  && .Key() != tcell.KeyTab &&
			.Key() != tcell.KeyBacktab && .Key() != tcell.KeyCtrlQ {
			 = 
		} else {
			 = .Capture()
		}
		if  == nil {
			if .Key() == tcell.KeyCtrlQ {
				return nil // quitting
			}

			// consumed by am-dbg; its handlers and states draw what changed
			.hDraw()
			return nil
		}
		if .Key() == tcell.KeyCtrlC {
			return  // let cview stop the app
		}

		// not handled by am-dbg: forward to the focused primitive and redraw
		// only the affected components
		 := .App.GetFocus()
		if  == nil {
			return 
		}
		 := .InputHandler()
		if  == nil {
			return 
		}
		(, .App.SetFocus)
		.hDraw(, .App.GetFocus())

		return nil
	})
}

func ( *Debugger) () *cbind.Configuration {
	// TODO remove?
	 := cbind.NewConfiguration()

	.App.SetAfterFocusFunc(func( cview.Primitive) {
		// add, but dont dup
		if !.Mach.WillBe1(ss.AfterFocus, am.PositionLast) {
			.Mach.Add1(ss.AfterFocus, Pass(&A{
				FocusPrimitive: ,
				MouseFocus:     .mouseFocusChanged,
			}))
		}

		.mouseFocusChanged = false
	})
	.App.SetMouseCapture(func(
		 *tcell.EventMouse,  cview.MouseAction,
	) (*tcell.EventMouse, cview.MouseAction) {
		if .Buttons() == tcell.ButtonPrimary {
			.mouseFocusChanged = true
		}

		return , 
	})

	 := func( string) func( *tcell.EventKey) *tcell.EventKey {
		return func( *tcell.EventKey) *tcell.EventKey {
			defer .Mach.PanicToErr(nil)

			// keep Tab inside dialogs
			if .Mach.Any1(states.DebuggerGroups.Dialog...) {
				return 
			}

			// fwd to App
			.Mach.Add1(, nil)
			return nil
		}
	}

	// TODO stop accepting keys if the actions arent processed in time

	// tab
	 := .Set("Backtab", (ss.FocusPrev))
	if  != nil {
		// TODO no log
		log.Printf("Error: binding keys %s", )
	}
	 = .Set("Tab", (ss.FocusNext))
	if  != nil {
		// TODO no log
		log.Printf("Error: binding keys %s", )
	}

	return 
}

// hSearchSchemaClients does search-as-you-type for a-z, -, _ in the tree and
// clientList, with a searchAsTypeWindow buffer.
// TODO split
func ( *Debugger) ( *cbind.Configuration) {
	var (
		 time.Time
		      string
		        = []string{"-", "_"}
	)

	for  := 0;  < 26; ++ {
		 = append(,
			fmt.Sprintf("%c", 'a'+))
	}

	for ,  := range  {
		 := 
		// TODO extract
		 := .Set(, func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Not(am.S{ss.ClientListFocused, ss.TreeFocused}) {
				return 
			}

			// buffer
			if .Add(searchAsTypeWindow).After(time.Now()) {
				 += 
			} else {
				 = time.Now()
				 = 
			}

			// find the first client starting with the key

			// sidebar
			if .Mach.Is1(ss.ClientListFocused) {
				 := .clientList.GetCurrentItemIndex()

				for ,  := range .clientList.GetItems() {
					if +1 <=  {
						continue
					}

					// TODO trim left and preserve position for multiple matches
					 := normalizeText(.GetMainText())
					if strings.HasPrefix(, ) {
						.clientList.SetCurrentItem()
						.hUpdateClientList()
						.hDraw(.clientList)
						break
					}
				}

				// TODO wrap search, extract
			} else if .Mach.Is1(ss.TreeFocused) {

				// tree
				 := false
				 := .tree.GetCurrentNode()
				// TODO optimize
				var  *cview.TreeNode
				.treeRoot.Walk(
					func(,  *cview.TreeNode,  int) bool {
						if  != nil {
							return false
						}
						if ! &&  !=  {
							return true

							// minimal match and move to next matches for speed
						} else if ! {
							 = true
						}

						 := normalizeText(.GetText())

						// check if branch is expanded
						 := 
						for  != nil {
							if !.IsExpanded() {
								return true
							}
							 = .GetParent()
						}

						// match found
						if strings.HasPrefix(, ) {
							 = 

							return false
						}

						return true
					},
				)

				if  != nil {
					// handle StateNameSelected
					,  := .GetReference().(*nodeRef)
					if  &&  != nil && .stateName != "" {
						.Mach.Add1(ss.StateNameSelected, Pass(&A{
							State: .stateName,
						}))
					} else {
						.Mach.Remove1(ss.StateNameSelected, nil)
					}
					.hUpdateSchemaTree()
					.hUpdateLogReader(nil)
					.hDraw()
					.tree.SetCurrentNode()
				}

				// TODO wrap search
			}

			return nil
		})
		if  != nil {
			log.Printf("Error: binding keys %s", )
		}
	}
}

// TODO move
type tcellKeyFn = func(ev *tcell.EventKey) *tcell.EventKey

func ( *Debugger) () map[string]tcellKeyFn {
	// TODO add state deps to the keystrokes structure
	// TODO use tcell.KeyNames instead of strings as keys
	// TODO rate limit
	 := tcell.KeyNames
	return map[string]func( *tcell.EventKey) *tcell.EventKey{
		// play/pause TODO select opt when toolbar focused
		"space": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Is1(ss.Paused) {
				.Mach.Add1(ss.Playing, nil)
			} else {
				.Mach.Add1(ss.Paused, nil)
			}

			return nil
		},

		// prev tx
		"left": .hPrevTxKey(),

		// next tx
		"right": .hNextTxKey(),

		// state jumps
		"alt+h":     .hJumpBackKey,
		"alt+l":     .hJumpFwdKey,
		"alt+Left":  .hJumpBackKey,
		"alt+Right": .hJumpFwdKey,

		// toggle mark on current tx
		"alt+i": func( *tcell.EventKey) *tcell.EventKey {
			// TODO not working?
			if .Mach.Is1(ss.ClientSelected) &&
				.Mach.Not(am.S{ss.ClientListFocused, ss.TreeFocused}) {
				.Mach.Add1(ss.ToggleMark, nil)

				return nil
			}
			return 
		},

		// markers jumps
		"alt+j": func( *tcell.EventKey) *tcell.EventKey {
			.Mach.Add1(ss.UserBackMarker, nil)

			return nil
		},
		"alt+k": func( *tcell.EventKey) *tcell.EventKey {
			.Mach.Add1(ss.UserFwdMarker, nil)

			return nil
		},

		// page up / down
		"alt+n": func( *tcell.EventKey) *tcell.EventKey {
			return tcell.NewEventKey(tcell.KeyPgDn, ' ', tcell.ModNone)
		},
		"alt+p": func( *tcell.EventKey) *tcell.EventKey {
			return tcell.NewEventKey(tcell.KeyPgUp, ' ', tcell.ModNone)
		},

		// expand / collapse trees
		"alt+e": func( *tcell.EventKey) *tcell.EventKey {
			// TODO race
			.hToolExpand()

			return nil
		},

		// log reader
		"alt+o": func( *tcell.EventKey) *tcell.EventKey {
			.Mach.Toggle1(ss.LogReaderEnabled, nil)

			return nil
		},

		// tail mode
		"alt+v": func( *tcell.EventKey) *tcell.EventKey {
			.Mach.Toggle1(ss.TailMode, nil)

			return nil
		},

		// matrix view
		"alt+m": func( *tcell.EventKey) *tcell.EventKey {
			.hToolMatrix()

			return nil
		},

		"alt+r": func( *tcell.EventKey) *tcell.EventKey {
			.Mach.Add1(ss.ToolRain, nil)

			return nil
		},

		// scroll to the first tx
		"home": func( *tcell.EventKey) *tcell.EventKey {
			// TODO race
			.hToolFirstTx(nil)

			return nil
		},

		// scroll to the last tx
		"end": func( *tcell.EventKey) *tcell.EventKey {
			// TODO race
			.hToolLastTx(nil)

			return nil
		},

		// quit the app
		"ctrl+q": func( *tcell.EventKey) *tcell.EventKey {
			.App.Stop()
			return nil
		},

		// help modal
		"?": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Not1(ss.HelpDialog) {
				.preModalFocus = .Focused
				.Mach.Add1(ss.HelpDialog, nil)
			} else {
				.Mach.Remove(states.DebuggerGroups.Dialog, nil)
			}

			return 
		},

		// focus filters bar
		"alt+f": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Not1(ss.Toolbar1Focused) {
				.App.SetFocus(.toolbars[0])
			} else {
				.App.SetFocus(.clientList)
			}
			.hDraw()

			return 
		},

		// export modal
		"alt+s": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Not1(ss.ExportDialog) {
				.Mach.Add1(ss.ExportDialog, nil)
			} else {
				.Mach.Remove(states.DebuggerGroups.Dialog, nil)
			}

			return 
		},

		// exit modals
		"esc": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Is1(ss.Overlay) {
				.Mach.Remove1(ss.Overlay, nil)
				return nil
			} else if .Mach.Any1(states.DebuggerGroups.Dialog...) {
				.Mach.Remove(states.DebuggerGroups.Dialog, nil)
				return nil
			}

			.hFocusDefault()

			return 
		},

		// remove client (sidebar)
		[tcell.KeyBackspace]: func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Not1(ss.ClientListFocused) {
				return 
			}

			// TODO race
			.hDeleteClient()
			return nil
		},

		// remove client (sidebar)
		"alt+d": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Not1(ss.ClientListFocused) {
				return 
			}

			// TODO race
			.hDeleteClient()
			return nil
		},

		// scroll to LogScrolled
		// scroll sidebar
		"down": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Is(S{ss.ClientListFocused, ss.ClientListVisible}) {
				.updateClientList()
			} else if .Mach.Is1(ss.LogFocused) {
				.Mach.Add1(ss.LogUserScrolled, nil)
			}

			return 
		},
		"up": func( *tcell.EventKey) *tcell.EventKey {
			if .Mach.Is(S{ss.ClientListFocused, ss.ClientListVisible}) {
				.updateClientList()
			} else if .Mach.Is1(ss.LogFocused) {
				.Mach.Add1(ss.LogUserScrolled, nil)
			}

			return 
		},
	}
}

func ( *Debugger) () {
	 := .clientList.GetCurrentItem()
	if  == nil || .Mach.Not1(ss.ClientListFocused) {
		return
	}

	 := .GetReference().(*clientListRef)
	.Mach.Add1(ss.RemoveClient, Pass(&A{
		ClientId: .name,
	}))
}

func ( *Debugger) () {
	 := false

	// default focus element
	if .Mach.Is1(ss.ClientListVisible) {
		if .Mach.Not1(ss.ClientListFocused) {
			.Mach.Add1(ss.ClientListFocused, nil)
			 = true
		}
	} else if .Mach.Not1(ss.TimelineTxHidden) {
		if .Mach.Not1(ss.TimelineTxsFocused) {
			.Mach.Add1(ss.TimelineTxsFocused, nil)
			 = true
		}
	} else if .Mach.Not1(ss.AddressFocused) {
		.Mach.Add1(ss.AddressFocused, nil)
		 = true
	}

	if  {
		.Mach.Add1(ss.UpdateFocus, nil)
	}
}

// these UI components can be navigated with keys
var keyNavigable = am.S{
	ss.AddressFocused, ss.Toolbar1Focused, ss.Toolbar2Focused, ss.Toolbar3Focused,
	ss.Toolbar4Focused,
}

func ( *Debugger) () tcellKeyFn {
	return func( *tcell.EventKey) *tcell.EventKey {
		// skip for log scrolling
		if .Mach.Is1(ss.LogFocused) {
			.Mach.Add1(ss.LogUserScrolled, nil)

			return 

			// skip for other UI components
		} else if .Mach.Any1(keyNavigable...) {
			return 
		}

		if .Mach.Not1(ss.ClientSelected) {
			return nil
		}
		if .hThrottleArrow() {
			return nil
		}

		// skip if scrolling
		if .hShouldScrollCurrView() {
			return 
		}

		// scroll timelines
		 := ss.UserFwd
		if .Mach.Is1(ss.TimelineMarkersFocused) {
			 = ss.UserFwdMarker
		}

		// check queue throttle and add the state
		if !.Mach.IsQueuedAbove(scrollTxThrottle, am.MutationAdd, S{}, false,
			false, 0) {

			.Mach.Add1(, nil)
		}

		return nil
	}
}

func ( *Debugger) () tcellKeyFn {
	return func( *tcell.EventKey) *tcell.EventKey {
		// skip for log scrolling
		if .Mach.Is1(ss.LogFocused) {
			.Mach.Add1(ss.LogUserScrolled, nil)

			return 

			// skip for other UI components
		} else if .Mach.Any1(keyNavigable...) {
			return 
		}

		if .Mach.Not1(ss.ClientSelected) {
			return nil
		}
		if .hThrottleArrow() {
			return nil
		}

		// skip if scrolling
		if .hShouldScrollCurrView() {
			return 
		}

		// scroll timelines
		 := ss.UserBack
		if .Mach.Is1(ss.TimelineMarkersFocused) {
			 = ss.UserBackMarker
		}

		// check queue throttle and add the state
		if !.Mach.IsQueuedAbove(scrollTxThrottle, am.MutationAdd, S{}, false,
			false, 0) {

			.Mach.Add1(, nil)
		}

		return nil
	}
}

func ( *Debugger) ( *tcell.EventKey) *tcell.EventKey {
	if .Mach.Not1(ss.ClientSelected) {
		return nil
	}
	if  != nil && .hThrottleKey(, arrowThrottleMs) {
		return nil
	}

	// TODO Start?
	 := .Mach.Context()
	.Mach.Remove(am.S{ss.Playing, ss.TailMode}, nil)

	if .Mach.Is1(ss.StateNameSelected) {
		 := ss.ScrollToMutTx
		// if d.Mach.Is1(ss.JumpTouch) {
		// 	state = ss.ScrollToTouchTx
		// }

		// state jump, dont block the event loop
		 := Pass(&A{
			State: .C.SelectedState,
			Fwd:   false,
		})
		.Mach.Go(, func() {
			amhelp.Add1Sync(, .Mach, , )
			// sidebar for errs TODO update in [state]
			.Mach.Eval("hJumpBackKey", func() {
				.hUpdateClientList()
			}, nil)
		})
	} else {
		// fast jump, dont block the event loop
		 := .hFastJumpCursor1(true)
		if  == .C.CursorTx1 {
			return nil
		}
		 := .C.CursorTx1 - 
		.Mach.Go(, func() {
			amhelp.Add1Sync(, .Mach, ss.Back, Pass(&A{
				Amount: ,
			}))
		})
	}

	return nil
}

func ( *Debugger) ( *tcell.EventKey) *tcell.EventKey {
	if .Mach.Not1(ss.ClientSelected) {
		return nil
	}
	if  != nil && .hThrottleKey(, arrowThrottleMs) {
		return nil
	}

	// TODO Start?
	 := .Mach.Context()
	.Mach.Remove(am.S{ss.Playing, ss.TailMode}, nil)

	if .Mach.Is1(ss.StateNameSelected) {
		 := ss.ScrollToMutTx
		// if d.Mach.Is1(ss.JumpTouch) {
		// 	state = ss.ScrollToTouchTx
		// }

		// state jump, dont block the event loop
		 := Pass(&A{
			State: .C.SelectedState,
			Fwd:   true,
		})
		.Mach.Go(, func() {
			amhelp.Add1Sync(, .Mach, , )
			// sidebar for errs TODO update in [state]
			.Mach.Eval("hJumpFwdKey", func() {
				.hUpdateClientList()
			}, nil)
		})
	} else {
		// fast jump, dont block the event loop
		 := .hFastJumpCursor1(false)
		if  == .C.CursorTx1 {
			return nil
		}
		 :=  - .C.CursorTx1
		.Mach.Go(, func() {
			amhelp.Add1Sync(, .Mach, ss.Fwd, Pass(&A{
				Amount: ,
			}))
		})
	}

	return nil
}

func ( *Debugger) () {
	 := .Mach.Is1
	 := .Mach.Not1
	switch {

	// default
	case (ss.TreeLogView):
		.Mach.Add1(ss.TreeMatrixView, nil)

	// small matrix
	case (ss.TreeMatrixView):
		if (ss.MatrixRain) {
			.Mach.Add1(ss.MatrixRain, nil)
		} else {
			// enlarge
			.Mach.Remove1(ss.MatrixRain, nil)
			.Mach.Add1(ss.MatrixView, nil)
		}

	// large matrix
	case (ss.MatrixView):
		if (ss.MatrixRain) {
			.Mach.Add1(ss.MatrixRain, nil)
		} else {
			// back to default
			.Mach.Add1(ss.TreeLogView, nil)
		}
	}
}

func ( *Debugger) ( *am.Event) {
	if .Mach.Not1(ss.ClientSelected) {
		return
	}
	.hSetCursor1(, &A{
		Cursor1:    len(.C.MsgTxs),
		FilterBack: true,
	})
	.Mach.EvRemove(, am.S{ss.TailMode, ss.Playing}, nil)
	// sidebar for errs
	.hUpdateClientList()
	.hRedrawFull(true)
}

func ( *Debugger) ( *am.Event) {
	if .Mach.Not1(ss.ClientSelected) {
		return
	}
	.hSetCursor1(, &A{Cursor1: 0})

	.Mach.EvRemove(, am.S{ss.TailMode, ss.Playing}, nil)
	// sidebar for errs
	.hUpdateClientList()
	.hRedrawFull(true)
}

func ( *Debugger) () {
	// log reader tree
	if .Mach.Is1(ss.LogReaderFocused) {
		 := .logReader.GetRoot()
		 := .GetChildren()
		 := false

		for ,  := range  {
			if .IsExpanded() {
				 = true
				break
			}
			.Collapse()
		}

		// memorize
		.C.ReaderCollapsed = 

		// TODO reader looses focus
		return
	}

	// schema tree
	 := false
	 := .tree.GetRoot().GetChildren()

	for ,  := range  {
		if .IsExpanded() {
			 = true
			break
		}
		.Collapse()
	}

	for ,  := range  {
		if  {
			.Collapse()
			.GetReference().(*nodeRef).expanded = false
		} else {
			.Expand()
			.GetReference().(*nodeRef).expanded = true
		}
	}

	// TODO maybe expand recursively?
}

func ( *Debugger) () bool {
	// always scroll matrix and log views
	return .Mach.Any1(ss.MatrixFocused, ss.LogFocused)
	// TODO scroll tree when relations expanded (support H scroll)
	// d.Mach.Is(am.S{ss.TreeFocused, ss.TimelineStepsScrolled})
}

// TODO optimize usage places
func ( *Debugger) ( *tcell.EventKey,  int) bool {
	// throttle TODO atomics
	 := .lastKeystroke == .Key()
	 := time.Since(.lastKeystrokeTime)
	if  &&  < time.Duration()*time.Millisecond {
		return true
	}

	.lastKeystroke = .Key()
	.lastKeystrokeTime = time.Now()

	return false
}

// hThrottleArrow lets the first arrow press through and then steps at most once
// per arrowRepeatMs while the key is held. A gap above arrowHoldWindowMs starts
// a new press.
func ( *Debugger) ( *tcell.EventKey) bool {
	// throttle TODO atomics
	 := time.Now()
	 := .lastKeystroke == .Key() &&
		.Sub(.lastKeystrokeTime) <= arrowHoldWindowMs*time.Millisecond
	if ! {
		.lastKeystroke = .Key()
		.lastKeystrokeTime = 
		return false
	}
	if .Sub(.lastKeystrokeTime) < arrowRepeatMs*time.Millisecond {
		return true
	}

	.lastKeystrokeTime = 

	return false
}

var _ = ss.FocusNext

// TODO move
func ( *Debugger) ( *am.Event) {
	 := slices.Index(.focusablePrims, .Focused)
	++
	if  >= len(.focusablePrims) {
		 = 0
	}
	 := .focusablePrims[]
	,  := .hBoxFromPrimitive()
	.Mach.EvAdd1(, , nil)
	.App.SetFocus()
}

var _ = ss.FocusPrev

// TODO move
func ( *Debugger) ( *am.Event) {
	 := slices.Index(.focusablePrims, .Focused)
	--
	// fallback to last one TODO log err
	if  < 0 {
		 = len(.focusablePrims) - 1
	}
	 := .focusablePrims[]
	,  := .hBoxFromPrimitive()
	.Mach.EvAdd1(, , nil)
	.App.SetFocus()
}

func ( *Debugger) () {
	var (
		 []*cview.Box
		 []cview.Primitive
	)
	// keep both lists in sync, so a Tab index always has a matching box
	 := func( cview.Primitive,  *cview.Box) {
		 = append(, )
		 = append(, )
	}

	// dialogs
	if .Mach.Is1(ss.ExportDialog) {
		(.exportDialog, .exportDialog.Box)
		.focusable, .focusablePrims = , 

		return
	} else if .Mach.Is1(ss.HelpDialog) {
		(.helpDialogLeft, .helpDialogLeft.Box)
		(.helpDialogRight, .helpDialogRight.Box)
		.focusable, .focusablePrims = , 

		return
	}

	// address bar
	(.addressBar, .addressBar.Box)

	// client list (hidden in narrow layout)
	if .Mach.Not1(ss.NarrowLayout) && .Mach.Is1(ss.ClientListVisible) {
		(.clientList, .clientList.Box)
	}

	// content panels, depending on the current view
	switch .Mach.Switch(states.DebuggerGroups.Views) {

	case ss.MatrixView:
		(.matrix, .matrix.Box)

	case ss.TreeMatrixView:
		(.treeGroups, .treeGroups.Box)
		(.treeFilterOut, .treeFilterOut.Box)
		(.tree, .tree.Box)
		(.matrix, .matrix.Box)

	default: // TreeLogView
		(.treeGroups, .treeGroups.Box)
		(.treeFilterOut, .treeFilterOut.Box)
		(.tree, .tree.Box)

		if .params.Filters.LogLevel != am.LogNothing {
			(.log, .log.Box)
		}
		if .Mach.Is1(ss.LogReaderVisible) {
			(.logReader, .logReader.Box)
		}
	}

	// timelines
	if .Mach.Not1(ss.TimelineTxHidden) {
		(.timelineTxs, .timelineTxs.Box)
	}
	if .Mach.Not1(ss.TimelineMarkersHidden) {
		(.timelineMarkers, .timelineMarkers.Box)
	}

	// toolbars
	for  := range .toolbars {
		(.toolbars[], .toolbars[].Box)
	}

	.focusable = 
	.focusablePrims = 
}