package main

import (
	"fmt"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"jygit.jydev.jianyu360.cn/data_processing/common_utils"
	"jygit.jydev.jianyu360.cn/data_processing/common_utils/log"
	"jygit.jydev.jianyu360.cn/data_processing/common_utils/mongodb"
	"jygit.jydev.jianyu360.cn/data_processing/common_utils/udp"
	"net"
	"os"
	"time"
)

var GF GlobalConf

func init() {
	InitConfig()
	InitLog()
	InitMgo()

	UdpClient = udp.UdpClient{Local: GF.Env.LocalPort, BufSize: 1024}
	nextAddr = &net.UDPAddr{
		Port: util.IntAll(GF.Env.NextPort),
		IP:   net.ParseIP(GF.Env.NextAddr),
	}
	UdpClient.Listen(processUdpMsg)
}

func InitConfig() (err error) {
	viper.SetConfigFile("config.toml") // 指定配置文件路径
	viper.SetConfigName("config")      // 配置文件名称(无扩展名)
	viper.SetConfigType("toml")        // 如果配置文件的名称中没有扩展名，则需要配置此项

	viper.AddConfigPath("./")
	viper.AddConfigPath("./conf/")  // 还可以在工作目录中查找配置
	viper.AddConfigPath("../conf/") // 还可以在工作目录中查找配置
	err = viper.ReadInConfig()      // 查找并读取配置文件
	if err != nil {                 // 处理读取配置文件的错误
		return
	}

	err = viper.Unmarshal(&GF)

	return err

}

func InitMgo() {
	now := time.Now()
	MgoB = &mongodb.MongodbSim{
		MongodbAddr: GF.MongoB.Host,
		DbName:      GF.MongoB.DB,
		Size:        GF.MongoB.Size,
		UserName:    GF.MongoB.Username,
		Password:    GF.MongoB.Password,
		Direct:      GF.MongoB.Direct,
	}
	MgoB.InitPool()

	log.Info("InitMgo", zap.Any("duration", time.Since(now).Seconds()))
}

func InitLog() {
	now := time.Now()
	err := log.InitLog(
		log.Path(GF.Log.LogPath),
		log.Level(GF.Log.LogLevel),
		log.Compress(GF.Log.Compress),
		log.MaxSize(GF.Log.MaxSize),
		log.MaxBackups(GF.Log.MaxBackups),
		log.MaxAge(GF.Log.MaxAge),
		log.Format(GF.Log.Format),
	)
	if err != nil {
		fmt.Printf("InitLog failed: %v\n", err)
		os.Exit(1)
	}

	log.Info("InitLog", zap.Any("duration", time.Since(now).Seconds()))
}
