package containers

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

func (c *Container) GetCodeSetting(r *Registry) (CodeSettingResp, error) {
	nodeInfo := r.nodeInfo.GetNodeInfo()
	if nodeInfo == nil {
		return CodeSettingResp{}, fmt.Errorf("[GetCodeSetting] Unknown node info.")
	}
	req := CodeSettingReq{
		AccountId: nodeInfo.AccountID,
		HostId:    nodeInfo.HostID,
		Appid:     c.AppInfo.AppIdHash.IntVal,
		AgentId:   c.AppInfo.AgentId,
	}
	//klog.Infof("[GetCodeSetting] req: %s.", utils.ToString(req))
	resp, err := r.connServer.GetCodeSetting(req)
	if err != nil {
		klog.WithError(err).Errorf("[GetCodeSetting] Failed GetCodeSetting  %s.", utils.ToString(req))
		return resp, err
	}

	//fmt.Println(resp)
	//c.saveWhiteStackSettingInfo(resp)
	return resp, err
}

func (c *Container) saveWhiteStackSettingInfo(resp CodeSettingResp) {
	c.WhiteSettingInfo.WhiteStackSettingInfo.WhiteList = resp.BlackWhiteSettings.WhiteList
	c.WhiteSettingInfo.WhiteStackSettingInfo.BlackList = resp.BlackWhiteSettings.BlackList
	c.WhiteSettingInfo.WhiteStackSettingInfo.OpenStack = resp.BlackWhiteSettings.CollectStack
}

func (c *Container) stackRuleUpdate(resp CodeSettingResp) bool {
	if c.noOrigRule() {
		return false
	}
	return resp.BlackWhiteSettings.WhiteList != c.WhiteSettingInfo.WhiteStackSettingInfo.WhiteList ||
		resp.BlackWhiteSettings.BlackList != c.WhiteSettingInfo.WhiteStackSettingInfo.BlackList
}

func (c *Container) noStackRule(resp CodeSettingResp) bool {
	return resp.BlackWhiteSettings.WhiteList == "" && resp.BlackWhiteSettings.BlackList == ""
}

func (c *Container) hasStackRule(resp CodeSettingResp) bool {
	return resp.BlackWhiteSettings.WhiteList != "" || resp.BlackWhiteSettings.BlackList != ""
}

func (c *Container) noOrigRule() bool {
	return c.WhiteSettingInfo.WhiteStackSettingInfo.WhiteList == "" && c.WhiteSettingInfo.WhiteStackSettingInfo.BlackList == ""
}
