package main

import (
	"embed"
	_ "embed"
	"log"

	updatesbootstrap "github.com/Eriyc/rules_wails/pkg/wails3kit/updates/bootstrap"
	updateswails "github.com/Eriyc/rules_wails/pkg/wails3kit/updates/wails"
	"github.com/wailsapp/wails/v3/pkg/application"
)

//go:embed all:frontend/dist
var assets embed.FS

func init() {
	updateswails.RegisterEvents("updates:state")
}

func main() {
	handled, err := updatesbootstrap.MaybeRun()
	if err != nil {
		log.Fatal(err)
	}
	if handled {
		return
	}

	appDescriptor, err := currentAppDescriptor()
	if err != nil {
		log.Fatal(err)
	}

	controller, err := newController(appDescriptor)
	if err != nil {
		log.Fatal(err)
	}

	var app *application.App
	updateService := NewUpdateService(updateswails.NewService(updateswails.Options{
		Controller: controller,
		EventName:  "updates:state",
		Emitter: func(name string, data any) {
			if app != nil {
				app.Event.Emit(name, data)
			}
		},
	}))

	app = application.New(application.Options{
		Name:        "updater-example",
		Description: "A Wails 3 updater example backed by the local update library",
		Services: []application.Service{
			application.NewService(updateService),
		},
		Assets: application.AssetOptions{
			Handler: application.AssetFileServerFS(assets),
		},
		Mac: application.MacOptions{
			ApplicationShouldTerminateAfterLastWindowClosed: true,
		},
	})

	app.Window.NewWithOptions(application.WebviewWindowOptions{
		Title: "Updater Example",
		Mac: application.MacWindow{
			InvisibleTitleBarHeight: 50,
			Backdrop:                application.MacBackdropTranslucent,
			TitleBar:                application.MacTitleBarHiddenInset,
		},
		BackgroundColour: application.NewRGB(244, 239, 230),
		URL:              "/",
	})

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