package containers

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

type AppInfoFromServerT struct {
	AppInfo *EbpfAppResp
	lock    *sync.RWMutex
}

var AppInfoFromServer AppInfoFromServerT

func init() {
	AppInfoFromServer = AppInfoFromServerT{
		AppInfo: new(EbpfAppResp),
		lock:    &sync.RWMutex{},
	}
}

func (r *Registry) PullAllAppInfo() {
	gcTicker := time.NewTicker(AllAppInfoInterval)
	defer gcTicker.Stop()
	for {
		select {
		case <-gcTicker.C:
			if !r.isFusing {
				req := EbpfAppReq{
					AccountId: r.nodeInfo.GetNodeInfo().AccountID,
				}
				res, err := r.connServer.PullAllAppInfo(req)
				if err != nil {
					klog.Errorf("PullAllAppInfo err: %v", err)
				}
				r.SaveAppinfos(&res)
				//fmt.Println(r.GetAppInfoByIpPort("12.3.1.2:9999"))
			}
		}
	}
}

func (r *Registry) SaveAppinfos(appinfos *EbpfAppResp) {
	AppInfoFromServer.lock.Lock()
	defer AppInfoFromServer.lock.Unlock()
	AppInfoFromServer.AppInfo = appinfos
}

func (r *Registry) GetAppInfoByIpPort(ipPort string) string {
	AppInfoFromServer.lock.Lock()
	defer AppInfoFromServer.lock.Unlock()
	if AppInfoFromServer.AppInfo == nil {
		return ""
	}
	info := *AppInfoFromServer.AppInfo
	if info == nil {
		return ""
	}
	appName, ok := info[ipPort]
	if ok {
		return appName
	}
	return ""
}

func (r *Registry) GetAllAppInfoFromServer() map[string]string {
	AppInfoFromServer.lock.Lock()
	defer AppInfoFromServer.lock.Unlock()
	appinfos := make(map[string]string)
	if AppInfoFromServer.AppInfo != nil {
		appinfos = *AppInfoFromServer.AppInfo
	}
	return appinfos
}
