package forcedstatus

import (
	"fmt"
	"io/ioutil"
	"os"
)

//ReasonService is an interface that abstracts the current state of the reason
//text files on the file system.
type ReasonService interface {
	GetReason(scope string, healthy bool) string
	Cleanup(scope string, healthy bool) error
	MkdirIfNecessary(scope string) error
}

func NewFileReasonService() *fileReasonService {
	return &fileReasonService{}
}

type fileReasonService struct {
}

//GetReason retrieves the reason text from the matching file on the file system, if it
//exists.  If the file doesn't exist or something bad happens, we just return an empty
//string.
func (reason *fileReasonService) GetReason(scope string, healthy bool) string {
	data, err := ioutil.ReadFile(fmt.Sprintf("./%s/%s", scope, healthString(healthy)))
	if err != nil {
		return ""
	}

	return string(data)
}

//Cleanup wipes out the reason file on the file system
func (reason *fileReasonService) Cleanup(scope string, healthy bool) error {
	err := os.Remove(fmt.Sprintf(fmt.Sprintf("./%s/%s", scope, healthString(healthy))))
	if os.IsNotExist(err) {
		return nil
	}
	return err
}

//MkdirIfNecessary is called on startup to verify that the folders for a reason scope
//exist on the file system
func (reason *fileReasonService) MkdirIfNecessary(scope string) error {
	pathStr := fmt.Sprintf("./%s", scope)
	_, err := os.Stat(pathStr)
	if os.IsNotExist(err) {
		return os.Mkdir(pathStr, 0777)
	}

	return err
}

func healthString(healthy bool) string {
	if healthy {
		return "healthy"
	}

	return "unhealthy"
}
