package nodes

import (
	"context"
	"encoding/json"
	"github.com/gogf/gf/v2/os/glog"
	"sparrow/pkg/protocol"
	"sparrow/pkg/ruleEngine"
)

type LogNodeConfig struct {
	Stdout bool `json:"stdout"` // 标准控制台输出
}

// LogNode 日志打印节点
type LogNode struct {
	config *LogNodeConfig
}

func (l *LogNode) Init(ctx ruleEngine.Context, config string) error {
	if config == "" {
		l.config = &LogNodeConfig{
			Stdout: false,
		}
	} else {
		c := new(LogNodeConfig)
		err := json.Unmarshal([]byte(config), c)
		if err != nil {
			return err
		}
		l.config = c
	}
	glog.SetPath("./log_nodes/")
	glog.SetStdoutPrint(false)
	return nil
}

func (l *LogNode) OnMessage(ctx ruleEngine.Context, message *protocol.Message) error {
	if l.config.Stdout {
		//l.mLog.Infof("日志节点：[设备ID：%s][消息类型：%s][消息内容：%s]", message.MetaData["device_id"], message.Type, message.Data)
		if did, ok := message.MetaData["device_id"]; ok {
			glog.File(did.(string)).Infof(context.Background(), "[消息类型：%s][消息内容：%s]", message.Type, message.Data)
		}
	}
	ctx.TellNext(message, protocol.Success)
	return nil
}
