package ui

import (
	"go_dreamfactory/cmd/v2/lib/storage"
	"go_dreamfactory/cmd/v2/service"
	"go_dreamfactory/cmd/v2/service/observer"
	"go_dreamfactory/cmd/v2/theme"
	"os"
	"sync"

	"fyne.io/fyne/v2"
	"github.com/BabySid/gobase"
	"github.com/sirupsen/logrus"
)

var uid string

type UI interface {
	AddWindow(name string, w fyne.Window)
	Run()
	Stop()
}

type UIImpl struct {
	app         fyne.App
	windows     map[string]fyne.Window
	winMux      *sync.Mutex
	connService service.ConnService
	pttService  service.PttService
	obs         observer.Observer
	storage     storage.Storage
	config      *storage.Config
}

func NewUI(app fyne.App,
	connService service.ConnService,
	pttService service.PttService,
	obs observer.Observer,
) (*UIImpl, error) {
	app.Settings().SetTheme(&theme.MyTheme{})

	iStorage, err := storage.NewOSStorage()
	if err != nil {
		logrus.Errorf("new storage err:%v", err)
		return nil, err
	}

	// 加载配置
	config, err := iStorage.LoadConfig()
	if err != nil {
		logrus.Errorf("Load config err:%v", err)
		return nil, err
	}
	return &UIImpl{
		app:         app,
		windows:     make(map[string]fyne.Window),
		winMux:      &sync.Mutex{},
		connService: connService,
		pttService:  pttService,
		obs:         obs,
		storage:     iStorage,
		config:      config,
	}, nil
}

func (ui *UIImpl) AddWindow(name string, w fyne.Window) {
	ui.winMux.Lock()
	defer ui.winMux.Unlock()
	ui.windows[name] = w
}

func (ui *UIImpl) Run() {
	defer func() {
		_ = os.Unsetenv("FYNE_SCALE")

		gobase.Exit()
	}()
	ui.app.Run()
}

func (ui *UIImpl) Stop() {
	ui.app.Quit()
}
