package cmii

import (
	"bytes"
	"io.wdd.message_pusher/pusher"
	"text/template"
)

type ImageSyncMessage struct {
	ImageFullName          string `json:"imageFullName"`
	ProjectName            string `json:"projectName"`
	ProjectNameSpace       string `json:"projectNameSpace"`
	ProjectMasterIP        string `json:"projectMasterIP"`
	ProjectMasterTopicName string `json:"projectMasterTopicName"`
	InnerWorkTopicName     string `json:"innerWorkTopicName"`
	CurrentProcedure       string `json:"currentProcedure"`
	IsSyncFinished         bool   `json:"isSyncFinished"`
}

const imageSyncTemplate = `
	{{if .IsSyncFinished}}
	镜像更新状态: 成功😍
	{{- else }}
	镜像更新状态: 失败👿👿👿
	{{- end}}
当前步骤: {{.CurrentProcedure}}
更新镜像: {{.ImageFullName}}
项目名称: {{.ProjectName}}
项目空间: {{.ProjectNameSpace}}
项目MasterIP: {{.ProjectMasterIP}}
项目Master名称: {{.ProjectMasterTopicName}}
中转节点名称: {{.InnerWorkTopicName}}
`

const ImageSyncTopicName = "imageSync"

var ImageSyncPushOptions = []pusher.PublishOption{
	pusher.WithTitle("镜像同步更新"),
	pusher.WithPriority("3"),
}

func (d *ImageSyncMessage) ParseTemplate() bytes.Buffer {
	// 解析模板
	tmpl, err := template.New("imageSyncTemplate").Parse(imageSyncTemplate)
	if err != nil {
		panic(err)
	}

	// 应用数据并打印结果
	var result bytes.Buffer
	err = tmpl.Execute(&result, d)
	if err != nil {
		panic(err)
	}

	return result
}

// PublishMessage 使用默认的Client 发布更新的消息
func (d *ImageSyncMessage) PublishMessage() *pusher.Message {

	parseTemplate := d.ParseTemplate()

	pusher.DefaultPusherClient.ChangeTopicName(ImageSyncTopicName)

	result, err := pusher.DefaultPusherClient.PublishDefault(parseTemplate, ImageSyncPushOptions)
	if err != nil {
		log.ErrorF("[ImageSyncMessage] - message push error ！ %s", err.Error())
		return result
	}

	return result

}
