package main

import (
	"context"
	"fmt"
	"git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/config"
	"git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/models"
	"git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/router"
	"git.kolaente.de/konrad/Konfi-Castle-Kasino/pkg/windows"
	"github.com/labstack/gommon/log"
	"os"
	"os/signal"
	"time"
)

func main() {
	//Startup Banner
	fmt.Println(`
################################################################
#  _   __             __ _         _____           _   _       #
# | | / /            / _(_)  ____ /  __ \         | | | |      #
# | |/ /  ___  _ __ | |_ _  / __ \| /  \/ __ _ ___| |_| | ___  #
# |    \ / _ \| '_ \|  _| |/ / _` + "`" + ` | |    / _` + "`" + ` / __| __| |/ _ \ #
# | |\  \ (_) | | | | | | | | (_| | \__/\ (_| \__ \ |_| |  __/ #
# \_| \_/\___/|_| |_|_| |_|\ \__,_|\____/\__,_|___/\__|_|\___| #
#                           \____/                             #
#                                                              #
#                _   __          _                             #
#               | | / /         (_)                            #
#               | |/ /  __ _ ___ _ _ __   ___                  #
#               |    \ / _` + "`" + ` / __| | '_ \ / _ \                 #
#               | |\  \ (_| \__ \ | | | | (_) |                #
#               \_| \_/\__,_|___/_|_| |_|\___/                 #
#                                                              #
#     © 2017-2019 Konrad Langenberg (konradlangenberg.de)      #
#                  Version: ` + models.Version + `                    #
################################################################`)

	// Config
	config.InitConfig()

	// DB init - Create tables
	models.DBinit()

	// Echo init
	e := router.NewEcho()
	router.RegisterRoutes(e)

	// Start server
	go func() {
		if err := e.Start(config.GetInterface()); err != nil {
			e.Logger.Info("shutting down...")
		}
	}()

	// Windows
	if config.GetOpenWindows() {
		go windows.OpenWindows()
	}

	if config.GetOpenBrowser() {
		go windows.OpenNativeWindows()
	}

	// Wait for interrupt signal to gracefully shutdown the server with
	// a timeout of 10 seconds.
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, os.Interrupt)
	<-quit
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	log.Infof("Shutting down...")
	if err := e.Shutdown(ctx); err != nil {
		e.Logger.Fatal(err)
	}
}
