package main

import (
	"math/rand"
	"os"
	"time"

	"github.com/gdamore/tcell"
	"github.com/rivo/tview"
)

const URLLogin = "https://auth.adlin.nemunai.re/login"

var (
	loggedAs = ""
)

func modal(p tview.Primitive, width, height int) tview.Primitive {
	return tview.NewFlex().
		AddItem(nil, 0, 1, false).
		AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
			AddItem(nil, 0, 1, false).
			AddItem(p, height, 1, false).
			AddItem(nil, 0, 1, false), width, 1, false).
		AddItem(nil, 0, 1, false)
}

func askLogin(app *tview.Application) {
	CreateLoginDialog(app, func(username, password string) {
		// Display check dialog
		CreateCheckDialog(app)

		go func() {
			if ok, err := checkLogin(username, password); ok {
				loggedAs = username
				app.Stop()
			} else {
				CreateErrMsgDialog(app, err)
			}
		}()
	})
}

func main() {
	// seed the rand package with time
	rand.Seed(time.Now().UnixNano())

	app := tview.NewApplication()

	app.SetInputCapture(func(event *tcell.EventKey) *tcell.EventKey {
		if event.Key() == tcell.KeyCtrlQ {
			app.Stop()
		}
		return event
	})

	if _, err := os.Stat("/sys/firmware/efi"); err != nil {
		CreateUEFIDialog(app, func() {
			askLogin(app)
		})
	} else {
		askLogin(app)
	}

	if err := app.Run(); err != nil {
		panic(err)
	}

	if loggedAs == "" {
		os.Exit(1)
	}

	runCinematic(loggedAs)
}
