package qq_message

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

// ShareMessage 链接分享消息
type ShareMessage struct {
	Type string           `json:"type"`
	Data ShareMessageData `json:"data"`
}

type ShareMessageData struct {
	URL     string `json:"url"`
	Title   string `json:"title"`
	Content string `json:"content,omitempty"`
	Image   string `json:"image,omitempty"`
}

func init() {
	RegisterMessageType(TypeShare, func() QQMessage {
		return NewShareMessage()
	})
}

func NewShareMessage() *ShareMessage {
	return &ShareMessage{Type: TypeShare}
}

func (msg *ShareMessage) GetMessageType() string {
	return TypeShare
}

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

func (msg *ShareMessage) ToCQString() string {
	base := fmt.Sprintf("[CQ:share,url=%s,title=%s", msg.Data.URL, msg.Data.Title)
	if msg.Data.Content != "" {
		base += fmt.Sprintf(",content=%s", msg.Data.Content)
	}
	if msg.Data.Image != "" {
		base += fmt.Sprintf(",image=%s", msg.Data.Image)
	}
	return base + "]"
}

func (msg *ShareMessage) ParseMessage(data string) error {
	re := regexp.MustCompile(`\[CQ:share,url=(.*?),title=(.*?)(?:,content=(.*?))?(?:,image=(.*?))?\]`)
	matches := re.FindStringSubmatch(data)
	if len(matches) < 3 {
		return fmt.Errorf("链接分享消息格式不正确")
	}
	msg.Data.URL = matches[1]
	msg.Data.Title = matches[2]
	if len(matches) > 3 {
		msg.Data.Content = matches[3]
	}
	if len(matches) > 4 {
		msg.Data.Image = matches[4]
	}
	return nil
}
