package main

import (
	"fmt"
	"strings"

	intcode "git.bullercodeworks.com/brian/adventofcode/2019/intcode-processor"
	"github.com/br0xen/termbox-screen"
	"github.com/br0xen/termbox-util"
	termbox "github.com/nsf/termbox-go"
)

const (
	MS_MODE_WAIT = iota
	MS_MODE_LOAD
	MS_MODE_RUN

	MS_MODES = 15

	MS_MODE_MENU = 1 << 4
)

type MainScreen struct {
	id    int
	title string
	mode  int

	filename string

	prog *intcode.Program
	menu []*MenuItem
}

func NewMainScreen() *MainScreen {
	m := &MainScreen{
		id:    ScreenIdMain,
		title: "IntCode Debugger",
		mode:  MS_MODE_WAIT,
	}
	m.menu = append(m.menu, NewMenu("File", NewMenu("Load"), NewMenu("Exit")))
	return m
}

func (screen *MainScreen) Id() int { return screen.id }

func (screen *MainScreen) Initialize(bundle termboxScreen.Bundle) error {
	return nil
}

func (screen *MainScreen) ResizeScreen() {
	screen.Initialize(nil)
}

func (screen *MainScreen) HandleNoneEvent(event termbox.Event) int {
	return screen.Id()
}

func (screen *MainScreen) HandleKeyEvent(event termbox.Event) int {
	if event.Ch == 0 && event.Key == termbox.KeyEsc {
		screen.toggleMenu()
	}
	return screen.Id()
}

// ╭╼╾╮
// │┼━│
// ├┴┬┤
// ╰──╯
func (screen *MainScreen) DrawScreen() {
	//w, _ := termbox.Size()
	screen.drawHeader()

	screen.drawFooter()
}

func (screen *MainScreen) drawHeader() {
	w, _ := termbox.Size()
	spaces := strings.Repeat(" ", ((w-len(screen.title))/2)+1)
	termboxUtil.DrawStringAtPoint(fmt.Sprintf("%s%s%s", spaces, screen.title, spaces), 0, 0, TitleFg, TitleBg)
	if screen.menuIsOn() {

	}
}

func (screen *MainScreen) drawFooter() {

}

func (screen *MainScreen) getMode() int {
	return screen.mode & MS_MODES
}

func (screen *MainScreen) menuIsOn() bool {
	return screen.mode&MS_MODE_MENU == MS_MODE_MENU
}

func (screen *MainScreen) toggleMenu() {
	if screen.menuIsOn() {
		screen.hideMenu()
	} else {
		screen.showMenu()
	}
}

func (screen *MainScreen) showMenu() {
	screen.mode = screen.mode | MS_MODE_MENU
}

func (screen *MainScreen) hideMenu() {
	screen.mode = screen.mode ^ MS_MODE_MENU
}

type MenuItem struct {
	title   string
	parent  string
	SubMenu []*MenuItem
}

func NewMenu(title string, items ...*MenuItem) *MenuItem {
	m := MenuItem{title: title}
	for i := range items {
		items[i].parent = title
		m.SubMenu = append(m.SubMenu, items[i])
	}
	return &m
}
