package qt

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 + "/.config/",
	}
	for _, o := range opt {
		o(a)
	}
	return a
}

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

func (a *Adapter) Generate(t themer.Theme) error {
	qssComponents := []string{
		"template.qss",
	}
	outputDir := filepath.Join(a.OutputDir, "qt6ct")
	if err := os.MkdirAll(outputDir, 0775); err != nil {
		return err
	}

	for _, component := range qssComponents {
		templatePath := filepath.Join("themer/adapters/qt", component)
		templ, err := template.ParseFiles(templatePath)
		if err != nil {
			return err
		}
		qssOutputDir := filepath.Join(outputDir, "qss")
		err = os.MkdirAll(qssOutputDir, 0775)
		if err != nil {
			return err
		}
		outputPath := filepath.Join(qssOutputDir, t.Meta.Name+".qss")

		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
		}
	}

	// 2. Generate qt5ct/qt6ct color scheme (.conf)
	confTemplatePath := "themer/adapters/qt/colors.conf"
	if _, err := os.Stat(confTemplatePath); err == nil {
		templ, err := template.ParseFiles(confTemplatePath)
		if err != nil {
			return err
		}
		confOutputDir := filepath.Join(outputDir, "colors")
		err = os.MkdirAll(confOutputDir, 0775)
		if err != nil {
			return err
		}
		outputPath := filepath.Join(confOutputDir, t.Meta.Name+".conf")
		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
		}
	}

	return nil
}
