// Copyright 2014 The gocui Authors. All rights reserved.
// Copyright 2017-2025 WIT.COM Inc. All rights reserved.
// Use of this source code is governed by the GPL 3.0

// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"errors"
	"fmt"
	"strings"

	"github.com/awesome-gocui/gocui"
	log "go.wit.com/log"
)

/*
	This in helpText doesn't print

	"\x1b[0;32m  \x1b[0m", // this was a test to see what might be
	// possible with gocui. it doesn't seem to work for me
*/

var helpText []string = []string{"Help Menu",
	"",
	"Tab: toggle through windows",
	"O:   toggle STDOUT",
	"H:   toggle this gocui menu",
	"L:   toggle light/dark mode",
	"CTRL-c: quit()",
	"",
	"Debugging:",
	"S: Supermouse mode",
	"M: list all widget positions",
	"L: list all widgets in tree",
}

func hideHelp() {
	if me.showHelp {
		log.Info("help is already down")
		me.showHelp = true
		return
	}
	me.showHelp = true
	me.baseGui.DeleteView("help")
}

func showHelp() error {
	if !me.showHelp {
		log.Info("help is already up")
		me.showHelp = false
		return nil
	}
	me.showHelp = false
	g := me.baseGui
	var err error
	maxX, _ := g.Size()

	var newW int = 8
	for _, s := range helpText {
		if newW < len(s) {
			newW = len(s)
		}
	}

	help, err := g.SetView("help", maxX-(newW+me.FramePadW), 0, maxX-1, len(helpText)+me.FramePadH, 0)
	if err != nil {
		if !errors.Is(err, gocui.ErrUnknownView) {
			return err
		}
		help.SelBgColor = gocui.ColorGreen
		help.SelFgColor = gocui.ColorBlack
		// fmt.Fprintln(help, "Enter: Click Button")
		// fmt.Fprintln(help, "Tab/Space: Switch Buttons")
		// fmt.Fprintln(help, "Backspace: Delete Button")
		// fmt.Fprintln(help, "Arrow keys: Move Button")

		fmt.Fprintln(help, strings.Join(helpText, "\n"))

		if _, err := g.SetCurrentView("help"); err != nil {
			return err
		}
	}
	g.SetViewOnTop("help")
	me.helpLabel = help
	if me.treeRoot == nil {
		log.Info("gogui makeClock() error. treeRoot == nil")
		return nil
	} else {
		if me.notify.clock.tk == nil {
			makeClock(me.notify.clock.wId)
			me.notify.clock.tk.MoveToOffset(maxX-10, 1)
			me.notify.clock.tk.Hide()
			me.notify.clock.tk.Show()
		}
		if me.notify.clock.tk != nil {
			me.notify.clock.tk.MoveToOffset(maxX-10, 1)
			me.notify.clock.tk.Hide()
			me.notify.clock.tk.Show()
		}
		if me.stdout.tk == nil {
			makeOutputWidget(me.baseGui, "made this in showHelp()")
			msg := fmt.Sprintf("test to stdout from in showHelp() %d\n", me.ecount)
			me.stdout.Write([]byte(msg))
			log.Log(NOW, "log.log(NOW) test")
		}
	}
	return nil
}