package main

import (
	"fmt"
	"os"

	"github.com/nsf/termbox-go"
)

const programName = "sqlite-browser"

var screenWidth int
var screenHeight int

type appState struct {
	m        *model
	isNewDB  bool
	filename string
}

var state *appState

func main() {
	var err error

	if len(os.Args) < 2 {
		printUsage()
		return
	}
	state = new(appState)

	if !canOpenDB(os.Args[1]) {
		fmt.Println("New DB?")
	}
	return

	state.isNewDB = !canOpenDB(os.Args[1])
	state.filename = os.Args[1]

	err = termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	style := defaultStyle()
	termbox.SetOutputMode(termbox.Output256)
	screenWidth, screenHeight = termbox.Size()
	mainLoop(style)
}

func mainLoop(style Style) {
	// Set up default screens
	screens := defaultScreens()
	displayScreen := screens[browserScreenIndex]
	layoutAndDrawScreen(displayScreen, style)

	for {
		// Handle User Input
		event := termbox.PollEvent()
		var newScreenIndex int
		if event.Type == termbox.EventKey {
			if event.Key == termbox.KeyCtrlC {
				break
			}
			newScreenIndex = displayScreen.handleEvent(event)
			if newScreenIndex < len(screens) {
				displayScreen = screens[newScreenIndex]
			} else if newScreenIndex == exitScreenIndex {
				break
			}
		}
		// Update Application State

		// (re)Draw Screen
		layoutAndDrawScreen(displayScreen, style)
	}
}

// Screens Setup
const (
	browserScreenIndex = iota
	aboutScreenIndex
	exitScreenIndex
)

func defaultScreens() []Screen {
	browserScreen := browserScreen{}
	aboutScreen := aboutScreen{}
	screens := []Screen{
		&browserScreen,
		&aboutScreen,
	}
	return screens
}

func defaultStyle() Style {
	var style Style
	style.defaultBg = termbox.ColorBlack
	style.defaultFg = termbox.ColorWhite
	style.titleFg = termbox.ColorBlack
	style.titleBg = termbox.ColorGreen
	style.cursorFg = termbox.ColorBlack
	style.cursorBg = termbox.ColorGreen

	return style
}

func printUsage() {
	fmt.Println("Usage: " + programName + " <sqlite file>")
}

// WriteToLog Writes to the Log
func WriteToLog(d string) {
	f, err := os.OpenFile(programName+".log", os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0664)
	if err != nil {
		panic(err)
	}
	f.WriteString(d)
	f.Close()
}