package main

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"

	"fyne.io/fyne/v2"
	"fyne.io/fyne/v2/app"
	"fyne.io/fyne/v2/canvas"
	"fyne.io/fyne/v2/container"
	"fyne.io/fyne/v2/layout"
	"fyne.io/fyne/v2/theme"
	"fyne.io/fyne/v2/widget"
)

type Project struct {
	Path string `json:"path"`
	Version float64 `json:"version"`
}

const jsonFilePath = "projects.json"

func loadProjects() ([]Project, error) {
	file, err := os.ReadFile(jsonFilePath)

	if err != nil {
		return nil, err
	}

	var projects []Project
	if err := json.Unmarshal(file, &projects); err != nil {
		return nil, err
	}

	return projects, nil
}

func main() {
	myApp := app.New()
	myWindow := myApp.NewWindow("Unreal Project Launcher")
	myWindow.Resize(fyne.NewSize(800, 600))

	projects, err := loadProjects()
	if err != nil {
		fmt.Println("Error while loading projects")
	}

	logText := widget.NewMultiLineEntry()
	logText.SetMinRowsVisible(5)
	logText.Disable()

	logMessage := func(msg string) {
		logText.SetText(logText.Text + msg + "\n")
	}

	var projectList *fyne.Container

	reloadUI := func() {
		projectList.RemoveAll()

		for _, project := range projects {
			projectName := filepath.Base(project.Path)
			iconPath := projectName + ".png"
			var projectIcon fyne.Resource

			if _, err := os.Stat(iconPath); err == nil {
				icon, err := fyne.LoadResourceFromPath(iconPath)
				if err == nil {
					projectIcon = icon
				}
			}

			if projectIcon == nil {
				projectIcon = theme.FileIcon()
			}

			icon := canvas.NewImageFromResource(projectIcon)
			icon.SetMinSize(fyne.NewSize(32, 32))

			nameLabel := widget.NewLabel(projectName)
			nameLabel.Alignment = fyne.TextAlignLeading

			generateBtn := widget.NewButton("Generate", func() {
				logMessage("Generate Project: " + projectName)
			})
			generateBtn.Resize(fyne.NewSize(150, 40))
			generateBtn.Size().Min(fyne.NewSize(150, 40))

			launchBtn := widget.NewButton("Start", func() {
				logMessage("Start Project " + projectName)
			})
			launchBtn.Size().Min(fyne.NewSize(150, 40))

			deleteBtn := widget.NewButton("X", func() {
				logMessage("Delete Project " + projectName)
			})

			row := container.NewHBox(
				icon,
				nameLabel,
				layout.NewSpacer(),
				generateBtn,
				launchBtn,
				deleteBtn,
			)

			projectList.Add(row)

		}
	}

	projectList = container.NewVBox()
	reloadUI()

	scrollContainer := container.NewVScroll(projectList)
	mainContainer := container.NewBorder(nil, logText, nil, nil, scrollContainer)

	myWindow.SetContent(mainContainer)
	myWindow.ShowAndRun()
}