package paths

import (
	"epochsilicon/pkg/log"
	"fmt"
	"os"
	"path/filepath"

	"epochsilicon/pkg/utils"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/dialog"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

const DefaultCrossOverPath = "/Applications/CrossOver.app"

var (
	CrossoverPath            string
	EpochPath                string
	PatchesAppliedEpoch      = false
	PatchesAppliedCrossOver  = false
	RosettaX87ServiceRunning = false
	ServiceStarting          = false
	DownloadingPatches       = false
)

func SelectCrossOverPath(myWindow fyne.Window, crossoverPathLabel *widget.RichText, updateAllStatuses func()) {
	dialog.ShowFolderOpen(func(uri fyne.ListableURI, err error) {
		if err != nil {
			dialog.ShowError(err, myWindow)
			return
		}
		if uri == nil {
			log.Info("CrossOver path selection cancelled.")
			updateAllStatuses()
			return
		}
		selectedPath := uri.Path()
		if filepath.Ext(selectedPath) == ".app" && utils.DirExists(selectedPath) {
			CrossoverPath = selectedPath
			PatchesAppliedCrossOver = false
			log.Infof("CrossOver path set to:", CrossoverPath)
			// Save to prefs
			prefs, _ := utils.LoadPrefs()
			prefs.CrossOverPath = selectedPath
			utils.SavePrefs(prefs)
		} else {
			dialog.ShowError(fmt.Errorf("invalid selection: '%s'. Please select a valid .app bundle", selectedPath), myWindow)
			log.Infof("Invalid CrossOver path selected:", selectedPath)
		}
		updateAllStatuses()
	}, myWindow)
}

func SelectEpochPath(myWindow fyne.Window, epochPathLabel *widget.RichText, updateAllStatuses func()) {
	dialog.ShowFolderOpen(func(uri fyne.ListableURI, err error) {
		if err != nil {
			dialog.ShowError(err, myWindow)
			return
		}
		if uri == nil {
			log.Info("Epoch path selection cancelled.")
			updateAllStatuses()
			return
		}
		selectedPath := uri.Path()
		if utils.DirExists(selectedPath) {
			EpochPath = selectedPath
			PatchesAppliedEpoch = false
			log.Infof("Epoch path set to:", EpochPath)
			// Save to prefs
			prefs, _ := utils.LoadPrefs()
			prefs.EpochPath = selectedPath
			utils.SavePrefs(prefs)
		} else {
			dialog.ShowError(fmt.Errorf("invalid selection: '%s' is not a valid directory", selectedPath), myWindow)
			log.Infof("Invalid Epoch path selected:", selectedPath)
		}
		updateAllStatuses()
	}, myWindow)
}

func UpdatePathLabels(crossoverPathLabel, EpochPathLabel *widget.RichText) {
	if CrossoverPath == "" {
		crossoverPathLabel.Segments = []widget.RichTextSegment{&widget.TextSegment{Text: "Not set", Style: widget.RichTextStyle{ColorName: theme.ColorNameError}}}
	} else {
		crossoverPathLabel.Segments = []widget.RichTextSegment{&widget.TextSegment{Text: CrossoverPath, Style: widget.RichTextStyle{ColorName: theme.ColorNameSuccess}}}
	}
	crossoverPathLabel.Refresh()

	if EpochPath == "" {
		EpochPathLabel.Segments = []widget.RichTextSegment{&widget.TextSegment{Text: "Not set", Style: widget.RichTextStyle{ColorName: theme.ColorNameError}}}
	} else {
		EpochPathLabel.Segments = []widget.RichTextSegment{&widget.TextSegment{Text: EpochPath, Style: widget.RichTextStyle{ColorName: theme.ColorNameSuccess}}}
	}
	EpochPathLabel.Refresh()
}

func CheckDefaultCrossOverPath() {
	if CrossoverPath == "" {
		if info, err := os.Stat(DefaultCrossOverPath); err == nil && info.IsDir() {
			CrossoverPath = DefaultCrossOverPath
			log.Infof("Pre-set CrossOver to default:", DefaultCrossOverPath)
		}
	}
}
