package handler

import (
	"fmt"
	"reflect"
	"strings"
)

var components map[string]interface{}

func Register(id string, comp interface{}) {
	fmt.Print("Register: ")
	if components == nil {
		components = make(map[string]interface{})
	}
	components[id] = comp
	fmt.Println(id, "+", components[id])
}

//输入string参数
//struct 类型需要解析[registerID].[field], 如:cluster.ClusterId
func AnalyseComponent(content string) interface{} {
	compMsg := strings.Split(content, ".")
	comp := components[compMsg[0]]
	//fmt.Println(compMsg,comp)
	//fmt.Println(comp, reflect.ValueOf(comp).Kind())

	if reflect.ValueOf(comp).Kind() == reflect.Struct {
		tmpType := reflect.ValueOf(comp).FieldByName(compMsg[1]).Type()
		//fmt.Println(tmpType)
		if tmpType == reflect.TypeOf("string") {
			//fmt.Println("isString")
			return reflect.ValueOf(comp).FieldByName(compMsg[1]).String()
		} else if tmpType == reflect.TypeOf(1) {
			//fmt.Println("isInt")
			//val := reflect.ValueOf(comp).FieldByName(compMsg[1]).Int()
			//fmt.Println(val)
			return reflect.ValueOf(comp).FieldByName(compMsg[1]).Int()
		}

	} else {
		return comp
	}
	return nil
}
