package utils

import (
	"os"

	"github.com/sirupsen/logrus"
	"gopkg.in/ini.v1"
)

// 缓存 timeZone 信息
var timeZoneCache string

// FileExists checks if a file exists and is not a directory before we
// try using it to prevent further errors.
func FileExists(filename string) bool {
	info, err := os.Stat(filename)
	if os.IsNotExist(err) {
		return false
	}
	return !info.IsDir()
}

// pbx 不能正确读取时区, 读取自定义文件  /etc/asterisk/ntp.conf
func GetLocationName() string {
	if timeZoneCache != "" {
		return timeZoneCache
	}
	filePath := "/etc/asterisk/ntp.conf"
	_, err := os.Stat(filePath)
	if err != nil {
		logrus.Error(err)
		return ""
	}
	iniFile, err := ini.Load(filePath)
	if err != nil {
		logrus.Error(err)
		return ""
	}
	timeZoneCache = iniFile.Section("ntp").Key("TZNAME").Value()
	logrus.Infof("use location %s", timeZoneCache)
	return timeZoneCache
}
