package logger

import (
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"os"
)

var logger *zap.Logger

func init() {
	encoder := zapcore.NewConsoleEncoder(DefaultEncoderConfig())
	multiWriteSyncer := zapcore.NewMultiWriteSyncer(DefaultConsoleSyncer())
	core := zapcore.NewCore(encoder, multiWriteSyncer, zapcore.DebugLevel)
	logger = zap.New(core, zap.AddCaller())
	defer func(logger *zap.Logger) {
		_ = logger.Sync()
	}(logger)
}

func DefaultTimeEncoder() (timeEncoder zapcore.TimeEncoder) {
	timeEncoder = zapcore.TimeEncoderOfLayout("2006-01-02 15:04:05.000")
	return
}

func DefaultEncoderConfig() (encoderConfig zapcore.EncoderConfig) {
	encoderConfig = zap.NewProductionEncoderConfig()
	encoderConfig.EncodeTime = DefaultTimeEncoder()
	encoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
	return
}

func DefaultConsoleSyncer() zapcore.WriteSyncer {
	return zapcore.AddSync(os.Stdout)
}

func Logger() *zap.SugaredLogger {
	sugarLogger := logger.Sugar()
	defer func(sugarLogger *zap.SugaredLogger) {
		err := sugarLogger.Sync()
		if err != nil {

		}
	}(sugarLogger)

	return sugarLogger
}
