package log

import (
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/tiptok/gocomm/config"
	logx "github.com/tiptok/gocomm/pkg/log"
	"log"
	"strings"
)

type ConsoleLog struct {
	//log *log.Logger
	config config.Logger
	depth  int
	level  int
}

func NewConsoleLog(config config.Logger, prefix string, depth int) logx.Log {
	if len(prefix) > 0 {
		log.SetPrefix(prefix)
	}
	log.SetFlags(log.LstdFlags | log.Lshortfile)
	return &ConsoleLog{
		config: config,
		depth:  depth,
		level:  beegoLogLevelAdapter(config.Level),
	}
}

func (this *ConsoleLog) Debug(args ...interface{}) {
	if this.level < logs.LevelDebug {
		return
	}
	log.Output(this.depth, this.appendAhead(args, "[D]"))
}

func (this *ConsoleLog) Info(args ...interface{}) {
	if this.level < logs.LevelInfo {
		return
	}
	log.Output(this.depth, this.appendAhead(args, "[I]"))
}

func (this *ConsoleLog) Warn(args ...interface{}) {
	if this.level < logs.LevelWarning {
		return
	}
	log.Output(this.depth, this.appendAhead(args, "[W]"))
}

func (this *ConsoleLog) Error(args ...interface{}) {
	if this.level < logs.LevelError {
		return
	}
	log.Output(this.depth, this.appendAhead(args, "[E]"))
}

func (this *ConsoleLog) Panic(args ...interface{}) {
	log.Output(this.depth, this.appendAhead(args, "[P]"))
}

func (this *ConsoleLog) Fatal(args ...interface{}) {
	log.Output(this.depth, this.appendAhead(args, "[F]"))
}

func (this *ConsoleLog) appendAhead(args []interface{}, addArgs ...interface{}) string {
	var rsp []interface{}
	rsp = append(rsp, addArgs...)
	rsp = append(rsp, args...)
	return fmt.Sprint(rsp...)
}

func beegoLogLevelAdapter(logLevel string) int {
	switch strings.ToUpper(logLevel) {
	case "DEBUG":
		return logs.LevelDebug
	case "INFO":
		return logs.LevelInformational
	case "WARN":
		return logs.LevelWarning
	case "ERROR":
		return logs.LevelError
	}
	return logs.LevelDebug
}