package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"unsafe"

	"github.com/getlantern/systray"
	"github.com/jchv/go-webview2/webviewloader"
	"golang.org/x/sys/windows"
)

func showError(msg string) {
	title, _ := windows.UTF16PtrFromString("u-desktop")
	text, _ := windows.UTF16PtrFromString(msg)
	procMessageBoxW.Call(0, uintptr(unsafe.Pointer(text)), uintptr(unsafe.Pointer(title)), 0x10)
}

func setupLog() {
	exePath, _ := os.Executable()
	logFile, err := os.Create(filepath.Join(filepath.Dir(exePath), "u-desktop.log"))
	if err != nil {
		return
	}
	log.SetOutput(logFile)
	log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
}

var version = "dev" // -ldflags "-X main.version=0.6.0"

func main() {
	setupLog()

	defer func() {
		if r := recover(); r != nil {
			log.Println("PANIC:", r)
			showError(fmt.Sprintf("程序崩溃: %v\n详情见 u-desktop.log", r))
		}
	}()

	ver, err := webviewloader.GetInstalledVersion()
	if err != nil || ver == "" {
		showError("未检测到 WebView2 运行时，请先安装 Microsoft Edge WebView2 Runtime。\n\n下载地址: https://developer.microsoft.com/microsoft-edge/webview2/")
		os.Exit(1)
	}
	log.Println("WebView2:", ver)

	mutexName, _ := windows.UTF16PtrFromString("Global\\u-desktop-single-instance")
	mutex, err := windows.CreateMutex(nil, false, mutexName)
	if err != nil {
		showError("创建互斥锁失败: " + err.Error())
		os.Exit(1)
	}
	if windows.GetLastError() == windows.ERROR_ALREADY_EXISTS {
		windows.CloseHandle(mutex)
		return
	}
	defer windows.CloseHandle(mutex)

	homeDir, _ := os.UserHomeDir()
	cfgDir := filepath.Join(homeDir, ".u-desktop")
	os.MkdirAll(cfgDir, 0755)
	configPath = filepath.Join(cfgDir, "settings.json")
	procSetProcessDPIAware.Call()

	log.Println("启动 systray...")
	systray.Run(onSystrayReady, nil)
}
