package hpc

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/svc"
	"gitlink.org.cn/JointCloud/pcm-coordinator/internal/types"
	"gitlink.org.cn/JointCloud/pcm-hpc/slurm"
)

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

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

func (l *CancelJobLogic) CancelJob(req *types.CancelJobReq) error {
	// todo: add your logic here and delete this line
	var clusterInfo *types.ClusterInfo
	tx := l.svcCtx.DbEngin.Raw("select * from t_cluster where id = ?", req.ClusterId).Scan(&clusterInfo)
	if tx.Error != nil {
		return tx.Error
	}
	client, err := slurm.NewClient(slurm.ClientOptions{
		URL:           clusterInfo.Server,
		ClientVersion: clusterInfo.Version,
		RestUserName:  clusterInfo.Username,
		Token:         clusterInfo.Token})
	if err != nil {
		return err
	}
	job, err := client.Job(slurm.JobOptions{})
	if err != nil {
		return err
	}
	err = job.CancelJob(slurm.CancelJobReq{JobId: req.JobId})
	if err != nil {
		return err
	}
	return nil
}
