package logger

import (
	"fmt"
	"os"
	"runtime"

	"github.com/kataras/iris/v12"
	"github.com/sirupsen/logrus"
	log "github.com/sirupsen/logrus"
)

var Logger *log.Logger
var LoggerEntry *log.Entry

// https://www.cnblogs.com/taoshihan/p/13846256.html
func init() {
	Logger = logrus.New()
	Logger.SetOutput(os.Stdout)
	Logger.SetFormatter(&log.JSONFormatter{})
	LoggerEntry = Logger.WithFields(log.Fields{
		"requestId": "",
		"trackId":   "",
		"userName":  "",
		"userId":    "",
		"file":      "",
	})
}

func SetLoggerEntry(ctx iris.Context) {
	LoggerEntry = Logger.WithFields(log.Fields{
		"requestId": ctx.Values().Get("requestId"),
		"trackId":   ctx.Values().Get("trackId"),
		"userName":  ctx.Values().Get("userName"),
		"userId":    ctx.Values().Get("userId"),
	})
}

func Warn(args ...interface{}) {
	File := ""
	_, file, line, ok := runtime.Caller(1)
	if ok {
		File = fmt.Sprintf("%s:%d", file, line)
	}
	LoggerEntry.WithFields(log.Fields{
		"file": File,
	}).Warn(args)
}

func Warnf(format string, args ...interface{}) {
	File := ""
	_, file, line, ok := runtime.Caller(1)
	if ok {
		File = fmt.Sprintf("%s:%d", file, line)
	}
	LoggerEntry.WithFields(log.Fields{
		"file": File,
	}).Warnf(format, args)
}

func Info(args ...interface{}) {
	File := ""
	_, file, line, ok := runtime.Caller(1)
	if ok {
		File = fmt.Sprintf("%s:%d", file, line)
	}
	LoggerEntry.WithFields(log.Fields{
		"file": File,
	}).Info(args)
}

func Infof(format string, args ...interface{}) {
	File := ""
	_, file, line, ok := runtime.Caller(1)
	if ok {
		File = fmt.Sprintf("%s:%d", file, line)
	}
	LoggerEntry.WithFields(log.Fields{
		"file": File,
	}).Infof(format, args)
}

func Error(args ...interface{}) {
	File := ""
	_, file, line, ok := runtime.Caller(1)
	if ok {
		File = fmt.Sprintf("%s:%d", file, line)
	}
	LoggerEntry.WithFields(log.Fields{
		"file": File,
	}).Error(args)
}

func Errorf(format string, args ...interface{}) {
	File := ""
	_, file, line, ok := runtime.Caller(1)
	if ok {
		File = fmt.Sprintf("%s:%d", file, line)
	}
	LoggerEntry.WithFields(log.Fields{
		"file": File,
	}).Errorf(format, args)
}
