package logger

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

var consoleLogCore *zap.Logger

type consoleLogger struct {
	logger *zap.Logger
}

func NewConsoleDriver(config console) (driver, error) {
	if consoleLogCore == nil {
		coreEncoder := zap.NewProductionEncoderConfig()
		coreEncoder.EncodeLevel = zapcore.CapitalLevelEncoder
		encoder := zapcore.NewJSONEncoder(coreEncoder)
		core := zapcore.NewCore(encoder, zapcore.Lock(os.Stdout), zap.DebugLevel)
		consoleLogCore = zap.New(core)
	}

	return &consoleLogger{consoleLogCore}, nil
}

func (c *consoleLogger) Record(message message) {
	if message.Level == debugLevel || message.Level == DebugLevel {
		c.logger.Debug(message.Content,
			zap.String("Extra", message.Extra),
			zap.Int("Pid", message.Pid),
			zap.String("Module", message.Module),
			zap.String("Operator", message.Operator),
			zap.String("Caller", message.Caller),
			zap.String("Date", message.Date),
			zap.String("Time", message.Time))
	} else if message.Level == infoLevel || message.Level == InfoLevel {
		c.logger.Info(message.Content,
			zap.String("Extra", message.Extra),
			zap.Int("Pid", message.Pid),
			zap.String("Module", message.Module),
			zap.String("Operator", message.Operator),
			zap.String("Caller", message.Caller),
			zap.String("Date", message.Date),
			zap.String("Time", message.Time))
	} else if message.Level == warnLevel || message.Level == WarnLevel {
		c.logger.Warn(message.Content,
			zap.String("Extra", message.Extra),
			zap.Int("Pid", message.Pid),
			zap.String("Module", message.Module),
			zap.String("Operator", message.Operator),
			zap.String("Caller", message.Caller),
			zap.String("Date", message.Date),
			zap.String("Time", message.Time))
	} else if message.Level == errorLevel || message.Level == ErrorLevel {
		c.logger.Error(message.Content,
			zap.String("Extra", message.Extra),
			zap.Int("Pid", message.Pid),
			zap.String("Module", message.Module),
			zap.String("Operator", message.Operator),
			zap.String("Caller", message.Caller),
			zap.String("Date", message.Date),
			zap.String("Time", message.Time))
	} else if message.Level == fatalLevel || message.Level == FatalLevel {
		c.logger.Fatal(message.Content,
			zap.String("Extra", message.Extra),
			zap.Int("Pid", message.Pid),
			zap.String("Module", message.Module),
			zap.String("Operator", message.Operator),
			zap.String("Caller", message.Caller),
			zap.String("Date", message.Date),
			zap.String("Time", message.Time))
	}
}
