package utils

import (
	"errors"

	"github.com/astaxie/beego/config"
	"github.com/astaxie/beego/logs"
)

var defaultLogger *logs.BeeLogger
var instances map[string]*logs.BeeLogger

// NewLog 构造日志对象
func NewLog(tp ...string) *logs.BeeLogger {
	logType := "common"
	if len(tp) > 0 {
		if tp[0] != "" {
			logType = tp[0]
		}
	}

	if v, ok := instances[logType]; ok {
		return v
	}

	log := logs.NewLogger()
	instances[logType] = log

	// 读取配置文件
	conf, err := config.NewConfig("ini", "./conf/log.conf")
	if err != nil {
		log.SetLogger(logs.AdapterConsole)
		return log
	}

	// 读文件存储位置
	filename := conf.String(logType + "::filename")
	// 输出级别
	level := conf.String(logType + "::level")
	if level == "" {
		level = "error"
	}

	if filename == "" {
		filename = "./" + logType + ".log"
	}

	log.Async()
	log.SetLogger(logs.AdapterFile, `{"filename":"`+filename+`"}`)
	return log
}

// LogError 错误日志
func LogError(v ...interface{}) error {
	log := instances["common"]

	if len(v) > 0 {
		firstV := v[0]
		leftV := v[1:]

		switch err := firstV.(type) {
		case string:
			log.Error(err, leftV...)
			return errors.New(err)
		case error:
			log.Error(err.Error(), leftV...)
			return err
		default:
			msg := "Unknown error type"
			log.Error(msg, leftV...)
			return errors.New(msg)
		}
	}

	return nil
}

// GetDefaultLogger 获取默认 logger
func GetDefaultLogger() *logs.BeeLogger {
	log := instances["common"]
	return log
}

func init() {
	instances = make(map[string]*logs.BeeLogger)
	NewLog()

	defaultLogger = GetDefaultLogger()
}
