package qq_message

import (
	"encoding/json"
	"fmt"
	"regexp"
)

// MfaceMessage QQ表情包消息
type MfaceMessage struct {
	Type string           `json:"type"`
	Data MfaceMessageData `json:"data"`
}

type MfaceMessageData struct {
	EmojiID        string `json:"emoji_id"`
	EmojiPackageID string `json:"emoji_package_id"`
	Key            string `json:"key"`
	Summary        string `json:"summary,omitempty"`
}

func init() {
	RegisterMessageType(TypeMface, func() QQMessage {
		return NewMfaceMessage()
	})
}

func NewMfaceMessage() *MfaceMessage {
	return &MfaceMessage{Type: TypeMface}
}

func (msg *MfaceMessage) GetMessageType() string {
	return TypeMface
}

func (msg *MfaceMessage) SetData(data json.RawMessage) error {
	return json.Unmarshal(data, &msg.Data)
}

func (msg *MfaceMessage) ToCQString() string {
	if msg.Data.Summary != "" {
		return fmt.Sprintf("[CQ:mface,emoji_id=%s,emoji_package_id=%s,key=%s,summary=%s]",
			msg.Data.EmojiID, msg.Data.EmojiPackageID, msg.Data.Key, msg.Data.Summary)
	}
	return fmt.Sprintf("[CQ:mface,emoji_id=%s,emoji_package_id=%s,key=%s]",
		msg.Data.EmojiID, msg.Data.EmojiPackageID, msg.Data.Key)
}

func (msg *MfaceMessage) ParseMessage(data string) error {
	re := regexp.MustCompile(`\[CQ:mface,emoji_id=(.*?),emoji_package_id=(.*?),key=(.*?)(?:,summary=(.*?))?\]`)
	matches := re.FindStringSubmatch(data)
	if len(matches) < 4 {
		return fmt.Errorf("表情包数据格式不正确")
	}
	msg.Data.EmojiID = matches[1]
	msg.Data.EmojiPackageID = matches[2]
	msg.Data.Key = matches[3]
	if len(matches) > 4 {
		msg.Data.Summary = matches[4]
	}
	return nil
}
