package nodes

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

// DeviceIdFilterNode 设备ID过滤节点
type DeviceIdFilterNode struct {
	config *DeviceIdFilterConfig
}

type DeviceIdFilterConfig struct {
	DeviceId    string `json:"device_id"`     // 设备ID
	SubDeviceId string `json:"sub_device_id"` // 子设备ID
}

func (d *DeviceIdFilterNode) Init(ctx ruleEngine.Context, config string) error {
	if config == "" {
		d.config = &DeviceIdFilterConfig{
			DeviceId:    "",
			SubDeviceId: "",
		}
	} else {
		c := new(DeviceIdFilterConfig)
		err := json.Unmarshal([]byte(config), c)
		if err != nil {
			return err
		}
		d.config = c
	}
	return nil
}

func (d *DeviceIdFilterNode) OnMessage(ctx ruleEngine.Context, message *protocol.Message) error {
	msgDeviceId, ok := message.MetaData["device_id"]
	if ok {
		if msgDeviceId.(string) != "" && msgDeviceId.(string) == d.config.DeviceId {
			ctx.TellNext(message, protocol.True)
			return nil
		} else {
			ctx.TellNext(message, protocol.False)
		}
	}
	//if msgSubDeviceId, ok := message.MetaData["sub_device_id"]; ok {
	//	if msgSubDeviceId.(string) == d.config.SubDeviceId {
	//		ctx.TellNext(message, protocol.True)
	//	}
	//}

	return nil
}
