package logger

import (
	"os"

	"gopkg.in/ini.v1"

	"github.com/natefinch/lumberjack"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

var lg *zap.Logger

var (
	mode       string
	level      string
	filename   string
	maxSize    int
	maxAge     int
	maxBackups int
)

func LoadLogConfig(file *ini.File) {
	logCfg := file.Section("zap_log")
	mode = logCfg.Key("mode").String()
	level = logCfg.Key("level").String()
	filename = logCfg.Key("filename").String()
	maxSize, _ = logCfg.Key("max_size").Int()
	maxAge, _ = logCfg.Key("max_age").Int()
	maxBackups, _ = logCfg.Key("max_backups").Int()
}

// ZapInit 初始化lg
func ZapInit(confPath string) {
	//从本地读取环境变量
	file, err := ini.Load(confPath)
	if err != nil {
		panic(err)
	}
	//加载数据库配置
	LoadLogConfig(file)
	writeSyncer := getLogWriter(filename, maxSize, maxBackups, maxAge)
	encoder := getEncoder()
	var l = new(zapcore.Level)
	err = l.UnmarshalText([]byte(level))
	if err != nil {
		return
	}
	var core zapcore.Core
	if mode == "dev" {
		// 进入开发模式，日志输出到终端
		consoleEncoder := zapcore.NewConsoleEncoder(zap.NewDevelopmentEncoderConfig())
		core = zapcore.NewTee(
			zapcore.NewCore(encoder, writeSyncer, l),
			zapcore.NewCore(consoleEncoder, zapcore.Lock(os.Stdout), zapcore.DebugLevel),
		)
	} else {
		core = zapcore.NewCore(encoder, writeSyncer, l)
	}

	lg = zap.New(core, zap.AddCaller())

	zap.ReplaceGlobals(lg)
	return
}

func getEncoder() zapcore.Encoder {
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder
	encoderConfig.TimeKey = "time"
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	encoderConfig.EncodeDuration = zapcore.SecondsDurationEncoder
	encoderConfig.EncodeCaller = zapcore.ShortCallerEncoder
	return zapcore.NewJSONEncoder(encoderConfig)
}

func getLogWriter(filename string, maxSize, maxBackup, maxAge int) zapcore.WriteSyncer {
	lumberJackLogger := &lumberjack.Logger{
		Filename:   filename,
		MaxSize:    maxSize,
		MaxBackups: maxBackup,
		MaxAge:     maxAge,
	}
	return zapcore.AddSync(lumberJackLogger)
}
