package main

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/knadh/koanf/providers/confmap"
	"github.com/knadh/koanf/providers/posflag"
	flag "github.com/spf13/pflag"

	"git.kemonine.info/PiFrame/config"
	"git.kemonine.info/PiFrame/ui"
)

func main() {
	// Command line flag handler
	f := flag.NewFlagSet("piframe", flag.ContinueOnError)
	f.Usage = func() {
		fmt.Println(f.FlagUsages())
		os.Exit(0)
	}
	// Command line flags
	f.Bool(config.CLI_FLAG_CONFIG_ONLY, false, "Only show the config UI, NOT the slideshow")
	cliFlag := f.Lookup(config.CLI_FLAG_CONFIG_ONLY)
	if cliFlag != nil {
		cliFlag.NoOptDefVal = "true"
	}
	// Process command line flags into handler
	f.Parse(os.Args[1:])

	// Load the config file
	pfConfig, configFileProvider := config.LoadConfig(false)

	// Watch for config changes and re-load config if needed
	configFileProvider.Watch(func(event interface{}, err error) {
		if err != nil {
			log.Printf("Error setting up watch of config : %s", err)
			return
		}

		// Give the config UI a chance to save and exit clean
		time.Sleep(time.Minute)

		// Bail on slideshow if there is a config change so it restarts with updated config
		log.Fatalf("Config file changed! Exiting!")
	})

	// Process command line flags
	if err := pfConfig.Load(posflag.Provider(f, ".", pfConfig), nil); err != nil {
		log.Fatalf("Error loading command line flags : %s", err)
	}

	hideSlideshow := pfConfig.Bool(config.CLI_FLAG_CONFIG_ONLY)

	// Reset the CLI flag so it's never writted to the config as 'true'
	pfConfig.Load(confmap.Provider(map[string]interface{}{
		config.CLI_FLAG_CONFIG_ONLY: false,
	}, "."), nil)

	if !hideSlideshow {
		ui.Slideshow(pfConfig)
	}

	ui.ConfigGui(pfConfig)
}
