package monitorsysresource

import (
	"encoding/json"
	"fmt"

	"be.ems/src/framework/cron"
	"be.ems/src/framework/logger"
	monitorService "be.ems/src/modules/monitor/service"
)

var NewProcessor = &MonitorSysResourceProcessor{
	monitorService: monitorService.NewMonitorImpl,
	count:          0,
	openDataCancel: false,
}

// MonitorSysResourceProcessor 系统资源CPU/IO/Netword收集
type MonitorSysResourceProcessor struct {
	// 服务器系统相关信息服务
	monitorService monitorService.IMonitor
	// 执行次数
	count int
	// 是否已经开启数据通道
	openDataCancel bool
}

func (s *MonitorSysResourceProcessor) Execute(data any) (any, error) {
	s.count++ // 执行次数加一
	options := data.(cron.JobData)
	sysJob := options.SysJob
	logger.Infof("重复 %v 任务ID %s", options.Repeat, sysJob.JobID)

	// 读取参数值
	var params struct {
		Interval float64 `json:"interval"`
	}
	err := json.Unmarshal([]byte(sysJob.TargetParams), &params)
	if err != nil {
		return nil, fmt.Errorf("json params 'interval' err: %v", err)
	}

	// 避免重复开启chan通道
	if !s.openDataCancel {
		s.monitorService.RunMonitorDataCancel(false, params.Interval)
		s.openDataCancel = true
	}

	s.monitorService.RunMonitor()

	// 返回结果，用于记录执行结果
	result := map[string]any{
		"count": s.count,
	}
	return result, nil
}
