package containers

import (
	"fmt"
	"github.com/coroot/coroot-node-agent/common"
	. "github.com/coroot/coroot-node-agent/utils/modelse"
	log "github.com/sirupsen/logrus"
)

type WhiteListMap map[string][]WhiteSettingInfo

func (r *Registry) getWhiteListByCodeType(codeType CodeType) []WhiteSettingInfo {
	//if true {
	//	return r.getWhiteListAll()
	//}
	return r.whiteListRules[codeType.WhiteCodeString()]
}

func (r *Registry) setWhiteList(whiteData WhiteData) {
	//var openStack int
	//if !r.tracer.DisableStackTracing() {
	//	openStack = 1
	//}
	whiteListMap := make(WhiteListMap)
	for _, scop := range whiteData.Appscope {
		code := scop.Code
		for _, setting := range scop.Settings {
			//setting.OpenStack = openStack
			whiteListMap[code] = append(whiteListMap[code], setting)
		}
	}
	r.whiteListRules = whiteListMap
}

func (r *Registry) pullWhiteList() (bool, error) {
	if r.isFusing {
		return false, nil
	}
	if common.IsOpenFilter() {
		return false, nil
	}
	//hostId, _ := utils.GetHostID()
	//fmt.Println(hostId)
	nodeInfo := r.nodeInfo.GetNodeInfo()
	if nodeInfo == nil {
		return false, fmt.Errorf("could not find node info")
	}
	whiteListReq := WhiteListReq{
		HostId:    nodeInfo.HostID,
		AccountId: nodeInfo.AccountID,
	}
	whiteData, err := r.connServer.WhiteList(whiteListReq)

	if err != nil {
		log.Errorf("report WhiteList info error is %v.", err)
		return false, err
	}

	//fmt.Println(r.whiteLastUpdatedTime)
	//fmt.Println(whiteData.LastUpdatedTime)
	// 不用更新
	if r.whiteLastUpdatedTime >= 0 && r.whiteLastUpdatedTime == whiteData.LastUpdatedTime {
		return false, nil
	}

	// 更新时间
	r.whiteLastUpdatedTime = whiteData.LastUpdatedTime

	r.setWhiteList(whiteData)
	return true, nil
}
