package main

import (
	"flag"
	"fmt"
	"os"

  _ "embed"
  "github.com/wailsapp/wails"
	"github.com/atotto/clipboard"
)

const (
	version string = "0.5.0"
)


//go:embed frontend/build/main.js
var js string

//go:embed frontend/build/main.css
var css string

var history *History = &History{make([]string, 0, 10), -1} 
var appCtrl *AppControl = &AppControl{} 
var settings *Settings = NewSettings()

type AppControl struct {
	runtime *wails.Runtime
}

func (f *AppControl) WailsInit(runtime *wails.Runtime) error {
	f.runtime = runtime
	log := f.runtime.Log.New("Goldberry")
	log.Info("AppIo initialized")
	return nil
}

func (f *AppControl) SaveFile(data string) error {
	filePath := f.runtime.Dialog.SelectSaveFile()
	if filePath == "" {
		return fmt.Errorf("Save canceled")
	}
	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()
	file.WriteString(data)

	return nil
}

func (f AppControl) WriteToClipboard(txt string) error {
	return clipboard.WriteAll(txt)
}

func (f *AppControl) OpenHTTP(url string) error {
	return f.runtime.Browser.OpenURL(url)
}

func (f *AppControl) Quit() {
	settings.Save()
	f.runtime.Window.Close()
}

func (f *AppControl) Fullscreen() {
	f.runtime.Window.Fullscreen()
}

func (f *AppControl) UnFullscreen() {
	f.runtime.Window.UnFullscreen()
}

func (f *AppControl) GetHomeText() (string, error) {
	return GoldberryHome()
}

func main() {
	versionFlag := flag.Bool("v", false, "Print the version number and exit")
	flag.Parse()
	if *versionFlag {
		fmt.Printf("Goldberry %s\n", version)
		os.Exit(0)
	}

  app := wails.CreateApp(&wails.AppConfig{
    Width:  1024,
    Height: 768,
    Title:  "Goldberry",
    JS:     js,
    CSS:    css,
		Colour: "#DAA520",
		Resizable: true,
		MinWidth: 400,
		MinHeight: 400,
		DisableInspector: false,
  })

	settings.Load()

  app.Bind(NavigateTo)
	app.Bind(history)
	app.Bind(appCtrl)
	app.Bind(settings)
  app.Run()
}
