package config

import (
	"log"
	"os"
	"text/template"
)

var (
	aliasTemplate = template.Must(template.New("base").Parse(`#!/usr/bin/env sh
# This file is generated by redo and includes active aliases.
`))
)

type Config struct {
	AliasPath   string
	ConfigDir   string
	HistoryPath string
	Editor      string
}

func (c *Config) FromEnv() {
	c.AliasPath = os.Getenv("REDO_ALIAS_PATH")
	c.ConfigDir = os.Getenv("REDO_CONFIG_PATH")
	c.HistoryPath = os.Getenv("REDO_HISTORY_PATH")
	c.Editor = os.Getenv("REDO_EDITOR")

	const defaultRedoConfigDir = "/redo"
	if c.ConfigDir == "" {
		dir, _ := os.UserConfigDir()
		c.ConfigDir = dir + defaultRedoConfigDir
	}
	if c.AliasPath == "" {
		c.AliasPath = c.ConfigDir + "/aliases"
	}
	if c.HistoryPath == "" {
		c.HistoryPath = os.Getenv("HISTFILE")
	}
	if c.Editor == "" {
		c.Editor = os.Getenv("EDITOR")
	}
}

func (c *Config) Validate() {
	if c.HistoryPath == "" {
		log.Fatalln("REDO_HISTORY_PATH or HISTFILE env variable must be set")
	}
	if c.Editor == "" {
		log.Fatalln("REDO_EDITOR or EDITOR env variable must be set")
	}
}

func (c *Config) EnsureAliasFileExists() error {
	if err := os.MkdirAll(c.ConfigDir, 0777); err != nil {
		return err
	}
	file, err := os.OpenFile(c.AliasPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
	if err != nil {
		return err
	}
	defer file.Close()

	stat, err := file.Stat()
	if err != nil {
		return err
	}
	if stat.Size() == 0 {
		return aliasTemplate.Execute(file, nil)
	}
	return nil
}
