package config

import (
	"fmt"
	"strings"

	"log"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

var GViper *viper.Viper

func InitViper(cfg string) *viper.Viper {
	v := viper.New()
	v.AutomaticEnv()
	v.SetEnvPrefix("sjy01_ip")
	v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

	v.SetConfigFile(cfg)
	v.SetConfigType("yaml")
	err := v.ReadInConfig()
	if err != nil {
		log.Println(fmt.Errorf("cannot read config file: %s, use default config", err.Error()))
		return nil
	}

	v.WatchConfig()

	v.OnConfigChange(func(e fsnotify.Event) {
		if err := v.Unmarshal(&GCONFIG); err != nil {
			fmt.Println(err)
		}

		log.Println("config file changed", e.Name, err)
	})

	if err := v.Unmarshal(&GCONFIG); err != nil {
		fmt.Println(err)
	}

	return v
}
