package main

import (
	"embed"
	"log"
	"net/http"

	"git.codemonkeysoftware.net/b/peachy-go/desktop/routes"
	"github.com/wailsapp/wails/v3/pkg/application"
)

//go:embed all:static
var assets embed.FS

func main() {

	r := routes.NewChiRouter()

	// Create the application
	app := application.New(application.Options{
		Name:        "Peachy",
		Description: "A demo of using raw HTML & CSS", // Description of the application
		Assets: application.AssetOptions{ // Assets to embed (our static files)
			Handler: application.AssetFileServerFS(assets),
			Middleware: func(next http.Handler) http.Handler {
				r.NotFound(next.ServeHTTP)
				return r
			},
		},
		Mac: application.MacOptions{
			ApplicationShouldTerminateAfterLastWindowClosed: true,
		},
	})

	// V3 introduces multiple windows, so we need to create a window
	app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{
		Title: "Your Project",
		Mac: application.MacWindow{
			Backdrop: application.MacBackdropTranslucent,
		},
		URL:      "/",  // URL to load when the window is created
		Width:    1080, // Width of the window
		Height:   720,  // Height of the window
		Centered: false,
	})

	menu := app.NewMenu()
	fileMenu := menu.AddSubmenu("File")
	fileMenu.AddRole(application.NewFile)
	fileMenu.AddRole(application.Open)
	fileMenu.Append(application.NewFileMenu().GetSubmenu())
	menu.FindByRole(application.NewFile).OnClick(func(ctx *application.Context) {
		d := application.SaveFileDialog()
		d.SetOptions(&application.SaveFileDialogOptions{
			Filters: []application.FileFilter{
				{DisplayName: "Peachy database", Pattern: "*.pit"},
				{DisplayName: "All Files", Pattern: "*.*"},
			},
			AllowOtherFileTypes: true,
			Title:               "Create new database",
		})
		path, err := d.PromptForSingleSelection()
		if err != nil {
			application.InfoDialog().SetMessage("Error: " + err.Error()).Show()
		}
		if path != "" {
			application.InfoDialog().SetMessage(path).Show()
		} else {
			application.InfoDialog().SetMessage("No file selected").Show()
		}
	})
	menu.FindByRole(application.Open).OnClick(func(ctx *application.Context) {
		path, _ := application.OpenFileDialog().
			CanChooseFiles(true).
			PromptForSingleSelection()
		if path != "" {
			application.InfoDialog().SetMessage(path).Show()
		} else {
			application.InfoDialog().SetMessage("No file selected").Show()
		}
	})
	app.SetMenu(menu)

	err := app.Run()

	if err != nil {
		log.Fatal(err)
	}
}
