/*
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 main

import (
	"fmt"
	"os"

	"github.com/gdamore/tcell"
)

type Ui struct {
	h, w int

	running bool
	tScreen tcell.Screen
	style   tcell.Style

	screen *UiScreen

	cursor int
}

func NewUi() *Ui {
	a := Ui{}
	err := a.init()
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}
	return &a
}

func (ui *Ui) init() error {
	var err error
	if ui.tScreen, err = tcell.NewScreen(); err != nil {
		return err
	}
	if err = ui.tScreen.Init(); err != nil {
		return err
	}

	ui.style = tcell.StyleDefault
	ui.tScreen.SetStyle(ui.style)
	ui.tScreen.Clear()

	ui.SetScreen(&UiScreen{})

	return nil
}

func (ui *Ui) run() error {
	ui.running = true

	for {
		if !ui.running {
			return nil
		}

		ui.tScreen.Clear()
		ui.screen.Draw()

		ui.tScreen.Show()

		// Poll Events
		ev := ui.tScreen.PollEvent()
		switch ev := ev.(type) {
		case *tcell.EventResize:
			ui.tScreen.Sync()
			ui.w, ui.h = ev.Size()
			ui.handleResize(ev)

		case *tcell.EventKey:
			if ev.Key() == tcell.KeyCtrlC {
				ui.stop()
				return nil
			}
			ui.screen.HandleKey(ev)

		case *tcell.EventTime:
			ui.screen.HandleTime(ev)
		}
	}
}

func (ui *Ui) handleResize(ev *tcell.EventResize) {
	ui.w, ui.h = ev.Size()
	ui.screen.HandleResize(ev)
}

func (ui *Ui) GetSize() (int, int) { return ui.tScreen.Size() }
func (ui *Ui) SetScreen(scr *UiScreen) {
	ui.screen = scr
	ui.screen.Init(ui)
	ui.screen.HandleResize(tcell.NewEventResize(ui.GetSize()))
}

func (ui *Ui) stop()    { ui.running = false }
func (ui *Ui) cleanup() { ui.tScreen.Fini() }
