package rofi

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: filepath.Join(home, ".themes"),
	}
	for _, o := range opt {
		o(a)
	}
	return a
}

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

func (a *Adapter) Generate(t themer.Theme) error {
	templatePath := filepath.Join("themer/adapters/rofi", "theme.rasi")
	templ, err := template.ParseFiles(templatePath)
	if err != nil {
		return err
	}
	outputPath := filepath.Join(a.OutputDir, t.Meta.Name, "rofi", "theme.rasi")

	if err := os.MkdirAll(filepath.Dir(outputPath), 0755); err != nil {
		return err
	}

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

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