package core

import (
	"context"
	"github.com/prometheus/common/model"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/tracker"
	"strconv"

	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type CenterResourcesLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCenterResourcesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CenterResourcesLogic {
	return &CenterResourcesLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CenterResourcesLogic) CenterResources() (*types.CenterResourcesResp, error) {
	resp := &types.CenterResourcesResp{}
	rawData, err := l.svcCtx.PromClient.GetRawData("center_top3", tracker.AdapterOption{})
	if err != nil {
		return nil, err
	}
	var centersIndex []*types.CenterIndex
	data := rawData.(model.Vector)
	for _, d := range data {
		for _, v := range d.Metric {
			num, err := strconv.ParseInt(string(v), 10, 64)
			if err != nil {
				return nil, err
			}
			centersIndex = append(centersIndex, &types.CenterIndex{Id: num})
		}
	}
	for _, centerIndex := range centersIndex {
		// Query the types of resource centers
		tx := l.svcCtx.DbEngin.Raw("select id,name,type as CenterType from t_adapter where id = ?", centerIndex.Id).Scan(&centerIndex)
		if tx.Error != nil {
			return nil, tx.Error
		}
		var clustersName string
		tx = l.svcCtx.DbEngin.Raw("SELECT GROUP_CONCAT(name SEPARATOR '|' ) as clustersName	  from t_cluster where adapter_id = ?", centerIndex.Id).Scan(&clustersName)
		if tx.Error != nil {
			return nil, tx.Error
		}
		cpuRawData, err := l.svcCtx.PromClient.GetRawData("center_cpu_utilisation", tracker.AdapterOption{AdapterId: centerIndex.Id, ClustersName: clustersName})
		cpuData := cpuRawData.(model.Vector)
		if err != nil {
			return nil, err
		}
		centerIndex.Cpu = cpuData[0].Value.String()
		memoryRawData, err := l.svcCtx.PromClient.GetRawData("center_memory_utilisation", tracker.AdapterOption{AdapterId: centerIndex.Id, ClustersName: clustersName})
		if err != nil {
			return nil, err
		}
		memoryData := memoryRawData.(model.Vector)

		centerIndex.Memory = memoryData[0].Value.String()
		diskRawData, err := l.svcCtx.PromClient.GetRawData("center_disk_utilisation", tracker.AdapterOption{AdapterId: centerIndex.Id, ClustersName: clustersName})
		if err != nil {
			return nil, err
		}
		diskData := diskRawData.(model.Vector)
		centerIndex.Storage = diskData[0].Value.String()
		resp.CentersIndex = append(resp.CentersIndex, *centerIndex)
	}
	return resp, nil
}
