package containers

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

func (r *Registry) getWhiteListAll() []WhiteSettingInfo {
	return r.whiteListRules["all"]
}

func (r *Registry) setWhiteListV2(whiteData WhiteDataV2) {
	whiteListMap := make(WhiteListMap)
	code := "all"
	for _, setting := range whiteData.SettingList {
		setting.Filters = setting.ProcessKey
		whiteListMap[code] = append(whiteListMap[code], setting)
	}
	r.whiteListRules = whiteListMap
}

func (r *Registry) pullWhiteListV2() (bool, error) {
	if r.isFusing {
		return false, nil
	}
	if common.IsOpenFilter() {
		return false, nil
	}
	nodeInfo := r.nodeInfo.GetNodeInfo()
	if nodeInfo == nil {
		return false, fmt.Errorf("could not find node info")
	}

	whiteListReq := WhiteListReq{
		HostId:    nodeInfo.HostID,
		AccountId: nodeInfo.AccountID,
		WhiteType: 2,
	}
	whiteData, err := r.connServer.WhiteListV2(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 == whiteData.LastUpdatedTime {
	//	return false, nil
	//}
	//
	//// 更新时间
	r.whiteLastUpdatedTime = whiteData.LastUpdatedTime
	r.setWhiteListV2(whiteData)
	saveRule(whiteData)
	return true, nil
}

func saveRule(runtimeApps WhiteDataV2) {
	appStr, _ := json.Marshal(runtimeApps)
	dumpPath := path.Join(utils.GetDefaultRuntimePath(), "memdump")
	err := os.MkdirAll(dumpPath, 0755)
	if err != nil {
		log.Error(err)
	}
	fileName := path.Join(dumpPath, "rule.snap")
	err = os.WriteFile(fileName, appStr, 0644)
	if err != nil {
		log.Error(err)
	}
}
