package nodes

import (
	"encoding/json"
	"sparrow/pkg/protocol"
	"sparrow/pkg/ruleEngine"
)

// MsgTypeFilterNode 消息类型过滤节点
// 如果当前消息的消息类型包含在当前节点的配置中，则使用True关系链，否则使用False关系
type MsgTypeFilterNode struct {
	config *MsgTypeFilterNodeConfig
}

type MsgTypeFilterNodeConfig struct {
	MessageTypes []string `json:"message_types"`
}

func (m *MsgTypeFilterNode) Init(ctx ruleEngine.Context, config string) error {
	if config == "" {
		m.config = &MsgTypeFilterNodeConfig{MessageTypes: []string{
			protocol.POST_ATTRIBUTES_REQUEST,
			protocol.POST_EVENT_REQUEST,
		}}
		return nil
	}
	c := new(MsgTypeFilterNodeConfig)
	err := json.Unmarshal([]byte(config), c)
	if err != nil {
		return err
	}
	m.config = c
	return nil
}

func (m *MsgTypeFilterNode) OnMessage(ctx ruleEngine.Context, message *protocol.Message) error {
	var relation protocol.RelationType
	var found bool
	for _, msgType := range m.config.MessageTypes {
		if message.Type == msgType {
			found = true
			break
		} else {
			found = false
			break
		}
	}
	if found {
		relation = protocol.True
	} else {
		relation = protocol.False
	}
	ctx.TellNext(message, relation)
	return nil
}
