/*

 Copyright (c) [2023] [pcm]
 [pcm-coordinator] is licensed under Mulan PSL v2.
 You can use this software according to the terms and conditions of the Mulan PSL v2.
 You may obtain a copy of Mulan PSL v2 at:
          http://license.coscl.org.cn/MulanPSL2
 THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 EITHER EXPaRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 See the Mulan PSL v2 for more details.

*/

package core

import (
	"context"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/constants"
	"gitlink.org.cn/JointCloud/pcm-coordinator/pkg/models"
	"k8s.io/apimachinery/pkg/util/json"
	"time"

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

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

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

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

func (l *ScheduleTaskByYamlLogic) ScheduleTaskByYaml(req *types.ScheduleTaskByYamlReq) (resp *types.ScheduleTaskByYamlResp, err error) {
	resp = &types.ScheduleTaskByYamlResp{}
	bytes, err := json.Marshal(req)
	if err != nil {
		return nil, err
	}
	// 构建主任务结构体
	taskModel := models.Task{
		Status:      constants.Saved,
		Description: req.Description,
		Name:        req.Name,
		YamlString:  string(bytes),
		CommitTime:  time.Now(),
		NsID:        req.NsID,
	}
	// 保存任务数据到数据库
	tx := l.svcCtx.DbEngin.Create(&taskModel)
	if tx.Error != nil {
		return nil, tx.Error
	}

	// 遍历子任务放入任务队列中
	for _, task := range req.Tasks {
		task.NsID = req.NsID
		task.TaskId = taskModel.Id

		// 将任务数据转换成消息体
		reqMessage, err := json.Marshal(task)
		if err != nil {
			logx.Error(err)
			return nil, err
		}
		publish := l.svcCtx.RedisClient.Publish(context.Background(), task.TaskType, reqMessage)
		if publish.Err() != nil {
			return nil, publish.Err()
		}
	}
	resp.TaskId = taskModel.Id
	return resp, nil
}
