package nodes

import (
	"reflect"
	"sparrow/pkg/ruleEngine"
)

var registerTypeMap = make(map[string]*item)

type item struct {
	T reflect.Type
	V reflect.Value
}

func init() {
	registerType((*MsgTypeFilterNode)(nil))
	registerType((*MsgTypeSwitchNode)(nil))
	registerType((*RestApiRequestNode)(nil))
	registerType((*FilterJavascriptNode)(nil))
	registerType((*InfluxDBNode)(nil))
	registerType((*MQTTBrokerNode)(nil))
	registerType((*DeviceIdFilterNode)(nil))
	registerType((*LogNode)(nil))
	registerType((*DingTalkRobotNode)(nil))
	registerType((*TempAlarmNode)(nil))
}

func registerType(elem interface{}) {
	v := reflect.ValueOf(elem)
	t := reflect.TypeOf(elem)
	registerTypeMap[t.Elem().Name()] = &item{
		T: t.Elem(),
		V: v,
	}
}

func CreateNodeByConfig(name string, ctx ruleEngine.Context, config string) (interface{}, bool) {
	item, ok := registerTypeMap[name]
	if !ok {
		return nil, false
	}
	var ptr reflect.Value
	ptr = reflect.New(item.T)
	temp := ptr
	initMethod := temp.MethodByName("Init")
	args := []reflect.Value{
		reflect.ValueOf(ctx),
		reflect.ValueOf(config),
	}
	initMethod.Call(args)
	return ptr.Interface(), true
}
