package ai

import (
	"context"
	"sort"

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

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

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

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

func (l *GetCenterQueueingLogic) GetCenterQueueing() (resp *types.CenterQueueingResp, err error) {
	resp = &types.CenterQueueingResp{}

	adapters, err := l.svcCtx.Scheduler.AiStorages.GetAdaptersByType("1")
	if err != nil {
		return nil, err
	}

	for _, adapter := range adapters {
		clusters, err := l.svcCtx.Scheduler.AiStorages.GetClustersByAdapterId(adapter.Id)
		if err != nil {
			continue
		}
		for _, cluster := range clusters.List {
			queues, err := l.svcCtx.Scheduler.AiStorages.GetClusterTaskQueues(adapter.Id, cluster.Id)
			if err != nil {
				continue
			}
			if queues == nil {
				continue
			}
			//todo sync current task queues
			current := &types.CenterQueue{
				Name:        cluster.Name,
				QueueingNum: int32(queues[0].QueueNum),
			}
			history := &types.CenterQueue{
				Name:        cluster.Name,
				QueueingNum: int32(queues[0].QueueNum),
			}
			resp.Current = append(resp.Current, current)
			resp.History = append(resp.History, history)

		}
	}

	sortQueueingNum(resp.Current)
	sortQueueingNum(resp.History)

	return resp, nil
}

func sortQueueingNum(q []*types.CenterQueue) {
	sort.Slice(q, func(i, j int) bool {
		return q[i].QueueingNum > q[j].QueueingNum
	})
}
