/*
Copyright © Brian Buller <brian@bullercodeworks.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package widgets

import (
	"fmt"
	"sort"
	"strings"

	wh "git.bullercodeworks.com/brian/tcell-widgets/helpers"
	"github.com/gdamore/tcell"
)

// Cli is a greedy widget and will consume all of the space you give it.
type Cli struct {
	id    string
	style tcell.Style

	x, y     int
	w, h     int
	active   bool
	visible  bool
	tabbable bool

	title       string
	rawLog      []string
	log         []string
	logPosition int

	value  string
	cursor int

	history         []string
	historyPosition int

	commands        []string
	commandMap      map[string]cliCommand
	commandGuessMap map[string]func(args ...string) string

	keyMap KeyMap
}

var _ Widget = (*Cli)(nil)

func NewCli(id string, s tcell.Style) *Cli {
	ret := &Cli{}
	ret.Init(id, s)
	return ret
}

func (w *Cli) Init(id string, s tcell.Style) {
	w.id, w.style = id, s
	w.visible = true
	w.initKeyMap()
	w.tabbable = true
}

func (w *Cli) Id() string { return w.id }
func (w *Cli) HandleResize(ev *tcell.EventResize) {
	w.w, w.h = ev.Size()
}

func (w *Cli) HandleKey(ev *tcell.EventKey) bool {
	if !w.active {
		return false
	}
	if wh.IsKey(*ev, tcell.KeyEsc) {
		w.SetActive(false)
		return true
	}
	if wh.IsBS(*ev) {
		if w.cursor > 0 {
			w.cursor--
		}
		if w.cursor < len(w.value) {
			w.value = w.value[:w.cursor] + w.value[w.cursor+1:]
		}
	}
	if ok := w.keyMap.Handle(ev); ok {
		return true
	}

	var ch string
	if wh.KeyIsDisplayable(*ev) {
		ch = string(ev.Rune())
		if w.cursor < len(w.value) {
			strPt1 := w.value[:w.cursor]
			strPt2 := w.value[w.cursor:]
			w.value = fmt.Sprintf("%s%s%s", strPt1, ch, strPt2)
		} else {
			w.value = fmt.Sprintf("%s%s", w.value, ch)
		}
		w.cursor++
		return true
	}
	return false
}
func (w *Cli) HandleTime(ev *tcell.EventTime) {}

func (w *Cli) Draw(screen tcell.Screen) {
	if !w.visible {
		return
	}
	dStyle := w.style
	if !w.active {
		dStyle = dStyle.Dim(true)
	}
	if w.title != "" {
		wh.TitledBorderFilled(w.x, w.y, w.x+w.w-1, w.y+w.h, w.title, wh.BRD_SIMPLE, dStyle, screen)
	} else {
		wh.BorderFilled(w.x, w.y, w.x+w.w-1, w.y+w.h, wh.BRD_SIMPLE, dStyle, screen)
	}

	x, y := w.x+1, w.y+1+w.h-3
	for i := 0; i < w.h-2; i++ {
		if len(w.log) > (i + w.logPosition) {
			idx := len(w.log) - (i + w.logPosition) - 1
			if idx < 0 {
				y--
				wh.DrawText(x, y, wh.PadR("", w.w-2), dStyle, screen)
				continue
			}
			line := w.log[idx]
			if len(line) > w.w-2 {
				line = line[:w.w-2]
			}
			wh.DrawText(x, y, wh.PadR(line, w.w-2), dStyle, screen)
			y--
		}
	}
	y = w.y + w.h - 1
	cursor := " "
	pre := "> "
	var post string
	if len(w.value) > 0 {
		pre = fmt.Sprintf("%s%s", pre, w.value[:w.cursor])
		if w.cursor < len(w.value) {
			cursor = string(w.value[w.cursor])
			post = w.value[w.cursor+1:]
		}
	}
	wh.DrawText(x, y, pre, dStyle, screen)
	x += len(pre)
	wh.DrawText(x, y, cursor, dStyle.Reverse(w.active), screen)
	x += 1
	wh.DrawText(x, y, wh.PadR(post, w.w-x-2), dStyle, screen)
	// wh.DrawText(w.x, y+1, fmt.Sprintf("Index: %d", w.historyPosition), dStyle, screen)
	// x += len(post) - 1
}

func (w *Cli) Active() bool       { return w.active }
func (w *Cli) SetActive(a bool)   { w.active = a }
func (w *Cli) Visible() bool      { return w.visible }
func (w *Cli) SetVisible(a bool)  { w.visible = a }
func (w *Cli) Focusable() bool    { return true }
func (w *Cli) SetTabbable(b bool) { w.tabbable = b }
func (w *Cli) Tabbable() bool     { return w.tabbable }
func (w *Cli) SetX(x int)         { w.x = x }
func (w *Cli) SetY(y int)         { w.y = y }
func (w *Cli) GetX() int          { return w.x }
func (w *Cli) GetY() int          { return w.y }
func (w *Cli) GetPos() Coord      { return Coord{X: w.x, Y: w.y} }
func (w *Cli) SetPos(c Coord)     { w.x, w.y = c.X, c.Y }
func (w *Cli) GetW() int          { return w.w }
func (w *Cli) GetH() int          { return w.h }
func (w *Cli) SetW(wd int)        { w.w = wd }
func (w *Cli) SetH(h int)         { w.h = h }
func (w *Cli) SetSize(c Coord)    { w.w, w.h = c.X, c.Y }
func (w *Cli) WantW() int         { return wh.MaxInt }
func (w *Cli) WantH() int         { return wh.MaxInt }
func (w *Cli) MinW() int          { return 20 }
func (w *Cli) MinH() int          { return 6 }

func (w *Cli) initKeyMap() {
	w.keyMap = NewKeyMap(map[tcell.Key]func(ev *tcell.EventKey) bool{
		tcell.KeyEsc: func(ev *tcell.EventKey) bool {
			w.SetActive(false)
			return true
		},
		tcell.KeyUp: func(ev *tcell.EventKey) bool {
			if w.historyPosition < len(w.history)-1 {
				w.historyPosition++
				w.value = w.history[w.historyPosition]
				w.cursor = len(w.value)
				return true
			}
			return false
		},
		tcell.KeyDown: func(ev *tcell.EventKey) bool {
			if w.historyPosition > -1 {
				w.historyPosition--
				if w.historyPosition == -1 {
					w.value = ""
				} else {
					w.value = w.history[w.historyPosition]
				}
				w.cursor = len(w.value)
				return true
			}
			return false
		},
		tcell.KeyLeft: func(ev *tcell.EventKey) bool {
			if w.cursor > 0 {
				w.cursor--
				return true
			}
			return false
		},
		tcell.KeyRight: func(ev *tcell.EventKey) bool {
			if w.cursor < len(w.value) {
				w.cursor++
				return true
			}
			return false
		},
		tcell.KeyCtrlU: func(ev *tcell.EventKey) bool {
			w.value = w.value[w.cursor:]
			w.cursor = 0
			return true
		},
		tcell.KeyTab: func(ev *tcell.EventKey) bool {
			// Auto-complete
			guess := w.findBestGuess()
			if guess != "" {
				w.value = guess
				w.cursor = len(w.value)
				return true
			}
			return false
		},
		tcell.KeyEnter: func(ev *tcell.EventKey) bool {
			cmds := strings.Split(w.value, " ")
			if v, ok := w.commandMap[cmds[0]]; ok {
				w.history = append(w.history, w.value)
				w.historyPosition = -1
				w.value = ""
				w.cursor = 0
				if len(cmds) > 1 {
					return v(cmds[1:]...)
				} else {
					return v()
				}
			}
			return true
		},
		tcell.KeyPgUp: func(ev *tcell.EventKey) bool {
			if w.historyPosition < len(w.log)-w.h-2 {
				w.historyPosition += (w.h - 2)
				if w.historyPosition > len(w.log) {
					w.historyPosition = len(w.log)
				}
				return true
			}
			return false
		},
		tcell.KeyPgDn: func(ev *tcell.EventKey) bool {
			if w.historyPosition > 0 {
				w.historyPosition -= (w.h - 2)
				if w.historyPosition < 0 {
					w.historyPosition = 0
				}
				return true
			}
			return false
		},
	})
}
func (w *Cli) SetTitle(ttl string) { w.title = ttl }
func (w *Cli) Title() string       { return w.title }
func (w *Cli) SetValue(val string) {
	w.value = val
	w.cursor = len(val)
}

func (w *Cli) AddComamnd(cmd string, do cliCommand) {
	w.commands = append(w.commands, cmd)
	sort.Strings(w.commands)
	w.commandMap[cmd] = do
}

func (w *Cli) RemoveCommand(cmd string) {
	var idx int
	for idx = range w.commands {
		if w.commands[idx] == cmd {
			break
		}
	}
	w.commands = append(w.commands[:idx], w.commands[idx+1:]...)
	delete(w.commandMap, cmd)
}

func (w *Cli) findBestGuess() string {
	if w.value == "" {
		return ""
	}
	for _, v := range w.commands {
		if strings.HasPrefix(v, w.value) {
			return v
		}
	}
	return ""
}

func (w *Cli) Log(txt string, args ...any) {
	val := fmt.Sprintf(txt, args...)
	w.rawLog = append(w.rawLog, val)
	w.log = append(w.log, wh.WrapStringToSlice(val, w.w-2)...)
}

func (w *Cli) Clear() {
	w.rawLog = []string{}
	w.log = []string{}
}

type cliCommand func(args ...string) bool

// TODO
func (c *cliCommand) findBestGuess(args ...string) string {
	_ = args
	return ""
}
