package rabbitmq

import (
	"encoding/json"
	"fmt"
	"wdd.io/agent-common/utils"
)

type IOctopusMessage interface {
	OctopusMsgHandler
	OctopusMsgSender
	OctopusMsgBuilder
}

type OctopusMsgSender interface {
	Send(rabbitQueue *RabbitQueue, msg []byte)

	SendToOctopusServer()
}

type OctopusMsgBuilder interface {
	Build(omType string, content interface{}) *OctopusMessage
}

type OctopusMessage struct {
	UUID               string      `json:"uuid"`
	InitTime           string      `json:"init_time" format:"2023-03-21 16:38:30"`
	OctopusMessageType string      `json:"octopusMessageType"`
	Content            interface{} `json:"content"`
	ACTime             string      `json:"ac_time" format:"2023-03-21 16:38:30"`
	Result             interface{} `json:"result"`
	ResultCode         string      `json:"resultCode"`
}

func (om *OctopusMessage) Send(rabbitQueue *RabbitQueue, msg []byte) {
	rabbitQueue.Send(msg)
}

// SendToOctopusServer send octopus message back to octopusToServer queue
func (om *OctopusMessage) SendToOctopusServer() {

	// write the octopus message to bytes
	octopusMessageReplayBytes, err := json.Marshal(om)
	if err != nil {
		log.ErrorF("replay octopus message write error => %v", err)
	}

	// Send back the result to queue
	OctopusToServerQueue.Send(octopusMessageReplayBytes)

}

func (om *OctopusMessage) Build(omType string, content interface{}) *OctopusMessage {

	// 当前时间
	curTimeString := utils.ParseDateTimeTime()

	// must write to string format, otherwise it's very hard to deserialize
	bytes, err := json.Marshal(content)
	if err != nil {
		fmt.Sprintf("OctopusMessage Build Error ! %v", err)
	}

	return &OctopusMessage{
		UUID:               curTimeString,
		InitTime:           curTimeString,
		OctopusMessageType: omType,
		Content:            string(bytes),
		Result:             nil,
		ACTime:             curTimeString,
	}
}
