package hpc

import (
	"context"
	"github.com/pkg/errors"
	"gitlink.org.cn/JointCloud/pcm-hpc/slurm"

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

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

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

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

func (l *JobInfoLogic) JobInfo(req *types.JobInfoReq) (resp *types.JobInfoResp, err error) {
	resp = &types.JobInfoResp{}
	var clusterInfo *types.ClusterInfo
	tx := l.svcCtx.DbEngin.Raw("select * from t_cluster where id = ?", req.ClusterId).Scan(&clusterInfo)
	if tx.Error != nil {
		return nil, tx.Error
	}
	client, err := slurm.NewClient(slurm.ClientOptions{
		URL:           clusterInfo.Server,
		ClientVersion: clusterInfo.Version,
		RestUserName:  clusterInfo.Username,
		Token:         clusterInfo.Token})
	if err != nil {
		return nil, err
	}
	job, err := client.Job(slurm.JobOptions{})
	if err != nil {
		return nil, err
	}
	jobResp, _ := job.GetJob(slurm.GetJobReq{JobId: req.JobId})

	if len(jobResp.Errors) != 0 {
		return nil, errors.Errorf(jobResp.Errors[0].Description)
	}
	resp.JobId = jobResp.Jobs[0].JobId
	resp.JobState = jobResp.Jobs[0].JobState
	resp.CurrentWorkingDirectory = jobResp.Jobs[0].CurrentWorkingDirectory
	return resp, nil
}
