package conf

import (
	"fmt"
	"os"
	"strconv"
	"strings"

	"work-device/log"

	"github.com/spf13/viper"
)

type AppConf struct {
	Redis struct {
		Addr     string
		Password string // no password set
		Db       int    // use default DB
	}
	System struct {
		Name            string
		Address         string
		MaxRoom         int
		MaxNativeRender int
	}
	Log struct {
		FileName    string
		Level       int32
		ServiceName string
	}
	Port  int32
	Mongo struct {
		DSN      string
		Database string
	}

	Debug struct {
		UserId    string
		UserPhone string
		UserRole  string
	}
	Obs struct {
		Bucket string
	}

	Nats struct {
		Url               string
		MaxReconnect      int
		ReconnDelaySecond int

		OsgconvStreamTopic string
		ShadowStreamTopic  string
		HdrProcStreamTopic string
		RenderStreamTopic  string
	}
}

func LoadConfFile(filepath string) (*AppConf, error) {
	file, err := os.Open(filepath)
	if err != nil {
		log.Errorf("can not open file:%s", filepath)
		return nil, err
	}
	v := viper.New()
	v.SetConfigType("yaml")
	err = v.ReadConfig(file)
	if err != nil {
		return nil, err
	}
	c := new(AppConf)
	err = v.Unmarshal(c)
	return c, err
}

func NewAppConf(filePath string) (*AppConf, error) {

	c, err := LoadConfFile(filePath)
	if err != nil {
		return c, err
	}

	//初始化log
	_ = log.NewLoggerSugar(c.Log.ServiceName, c.Log.FileName, c.Log.Level)

	//环境变量
	mongo := os.Getenv("MONGO")
	fmt.Println("env MONGO=>", mongo)

	if len(mongo) > 0 {
		c.Mongo.DSN = mongo
		//解析出database mongodb://admin:123456@124.70.148.113:27018/sku3d_dadong?authSource=admin
		start := strings.LastIndex(mongo, "/")
		end := strings.LastIndex(mongo, "?")
		database := mongo[start+1 : end]
		if len(database) > 0 {
			c.Mongo.Database = database
		}
		fmt.Println(c.Mongo.DSN, c.Mongo.Database)
	}
	//redis
	redis := os.Getenv("REDIS")
	fmt.Println("Env REDIS=>", redis)

	if len(redis) > 0 {
		c.Redis.Addr = redis
		start := strings.LastIndex(redis, "/")
		if start > 0 {
			db := redis[start:]
			dbint, _ := strconv.Atoi(db)
			c.Redis.Db = dbint
			c.Redis.Addr = string(redis[0:start])
		}

		fmt.Println(c.Redis.Addr, c.Redis.Db)
	}
	//rabbitmq
	nats := os.Getenv("NATS")
	if len(nats) > 0 {
		c.Nats.Url = nats
	}

	fmt.Println("Env NATS=>", nats)
	AppConfig = c

	return c, nil
}

var AppConfig *AppConf = nil
