package logs

import (
	"os"

	"golib/v2/log"
)

// 操作日志: 做了什么动作
// 安全日志: 登录/修改密码/权限等
// 设备日志: 设备之间的通信及启动等操作, 联网等
// 运行日志: 文本

const (
	Action = "[Action]" // Action 操作日志: 做了什么动作
	Safety = "[Safety]" // Safety 安全日志: 登录/修改密码/权限等
	Device = "[Device]" // Device 设备日志: 设备之间的通信及启动等操作, 联网等

	All = "[All] " // 其他
)

var (
	Console = NewStdout()
)

type Logs struct {
	Path      string
	sessionID string
	log       log.Prefix
}

func (c *Logs) prepend(tag, f string) string {
	return tag + " " + f
}

func (c *Logs) Session() *Logs {
	return &Logs{sessionID: NewSessionID(), log: c.log}
}

func (c *Logs) Prefix(prefix string, f string, v ...any) {
	c.log.Prefix(prefix, f, v...)
}

// Println 使用此方法打印不会被分析
func (c *Logs) Println(f string, v ...any) {
	if len(c.sessionID) == 0 {
		c.log.Println(f, v...)
		return
	}
	c.log.Prefix(c.sessionID, f, v...)
}

// Action 操作日志
func (c *Logs) Action(f string, v ...any) {
	if len(c.sessionID) == 0 {
		c.log.Prefix(Action, f, v...)
		return
	}
	c.log.Prefix(c.sessionID, c.prepend(Action, f), v...)
}

// Safety 安全日志
func (c *Logs) Safety(f string, v ...any) {
	if len(c.sessionID) == 0 {
		c.log.Prefix(Safety, f, v...)
		return
	}
	c.log.Prefix(c.sessionID, c.prepend(Safety, f), v...)
}

// Device 设备日志
func (c *Logs) Device(f string, v ...any) {
	if len(c.sessionID) == 0 {
		c.log.Prefix(Device, f, v...)
		return
	}
	c.log.Prefix(c.sessionID, c.prepend(Device, f), v...)
}

// NewStdout 默认输出到控制台, 通常在整体代码未初始化时作为默认值使用
func NewStdout() *Logs {
	logs := &Logs{
		log: log.New(os.Stdout, "", 4),
	}
	return logs
}

func New(tag, path string) *Logs {
	logs := &Logs{
		Path: path,
		log:  log.New(log.NewFileWriter(tag, path), "", 3),
	}
	return logs
}
