package containers

import (
	"fmt"
	"runtime"
	"time"

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

func (r *Registry) RegisterHost() error {
	// 注册
	nodeInfo := r.nodeInfo.GetNodeInfo()
	if nodeInfo == nil {
		return fmt.Errorf("could not find node info")
	}
	req := RegisterHostReq{
		LicenseKey:    nodeInfo.LicenseKey,
		HostId:        nodeInfo.HostID,
		HostIp:        nodeInfo.HostIp,
		HostName:      nodeInfo.Hostname,
		HostNameAlias: nodeInfo.Hostname,
		HostType:      1,
		Version:       nodeInfo.AgentVersion,
		SysVersion:    runtime.GOOS + " " + runtime.GOARCH,
		SystemUuid:    nodeInfo.SystemUUID,
		Ebpf:          true,
		AgentType:     2020,
	}
	accountID, err := r.connServer.RegisterHost(req)
	if err != nil {
		return err
	}

	// 更新nodeInfo中的AccountID
	if r.nodeInfo != nil {
		r.nodeInfo.AccountID = accountID
		klog.Infof("[register host] Updated account_id to %d", accountID)
	}

	return nil
}

func (r *Registry) TaskRegisterHost() {
	gcTicker := time.NewTicker(RegisterHostInterval)
	defer gcTicker.Stop()
	for {
		select {
		case <-gcTicker.C:
			//_, err1 := os.Stat("/tmp/fuse")
			//if err1 == nil {
			//	//r.isFusing = true
			//	r.DoFusing()
			//} else {
			//	r.DoResume()
			//	//r.isFusing = false
			//}
			err := r.RegisterHost()
			if err != nil {
				klog.WithError(err).Error("[task] Failed to register host")
			}
		}
	}
}
