package gtk

import (
	"Sithego/themer"
	"os"
	"path/filepath"
	"text/template"
)

type Adapter struct {
	OutputDir string
}

type Option func(*Adapter)

func WithOutputDir(dir string) Option {
	return func(a *Adapter) {
		a.OutputDir = dir
	}
}

func New(opt ...Option) *Adapter {
	home, _ := os.UserHomeDir()
	a := &Adapter{
		OutputDir: home + "/.themes/",
	}
	for _, o := range opt {
		o(a)
	}
	return a
}

func (a *Adapter) Name() string {
	return "GTK"
}

func (a *Adapter) Generate(t themer.Theme) error {
	components := []string{
		"template.css",
		"components/base.css",
		"components/headerbar.css",
		"components/buttons.css",
		"components/entries.css",
		"components/menus.css",
		"components/widgets.css",
		"components/checks.css",
		"components/scrollbars.css",
		"components/notebook.css",
	}

	outputDir := a.OutputDir + t.Meta.Name + "/gtk-3.0"
	_ = os.RemoveAll(outputDir)
	outputGTK4 := a.OutputDir + t.Meta.Name + "/gtk-4.0"
	_ = os.RemoveAll(outputGTK4)

	if err := os.MkdirAll(outputDir, 0775); err != nil {
		return err
	}

	for _, component := range components {
		templatePath := filepath.Join("themer/adapters/gtk", component)
		templ, err := template.ParseFiles(templatePath)
		if err != nil {
			return err
		}

		outputName := filepath.Base(component)
		if outputName == "template.css" {
			outputName = "gtk.css"
		}
		outputPath := filepath.Join(outputDir, outputName)

		file, err := os.Create(outputPath)
		if err != nil {
			return err
		}

		err = templ.Execute(file, struct {
			Theme themer.Theme
		}{
			Theme: t,
		})
		_ = file.Close()
		if err != nil {
			return err
		}
	}

	if err := os.MkdirAll(outputGTK4, 0775); err != nil {
		return err
	}
	return os.CopyFS(outputGTK4, os.DirFS(outputDir))
}
