package action

import (
	"encoding/json"
	"fmt"
	"log"
	"strconv"
	"sync"
	"time"

	"git.lxtend.com/lixiangwuxian/qqbot/model"
	"git.lxtend.com/lixiangwuxian/qqbot/qq_message"
	"github.com/gorilla/websocket"
)

func init() {
}

var ActionManager = actionManager{}

type actionManager struct {
	botConn *websocket.Conn
	sendMtx sync.Mutex
}

func (am *actionManager) Started() bool {
	return am.botConn != nil
}

func (am *actionManager) SetConn(conn *websocket.Conn) {
	am.botConn = conn
}

func (am *actionManager) SendAction(action string) error {
	return am.botConn.WriteMessage(websocket.TextMessage, []byte(action))
}

func (am *actionManager) SendMsg(reply *model.Reply) error {
	am.sendMtx.Lock()
	defer am.sendMtx.Unlock()
	if reply.ReferOriginMsg {
		replyMsg := qq_message.ReplyMessage{
			Type: "reply",
			Data: qq_message.ReplyMessageData{
				ID: int(reply.FromMsg.OriginMsgId),
			},
		}
		switch replyMsgVal := reply.ReplyMsg.(type) {
		case []any:
			reply.ReplyMsg = append([]any{replyMsg}, replyMsgVal...)
		case string:
			reply.ReplyMsg = fmt.Sprintf("%s%s", replyMsg.ToCQString(), replyMsgVal)
		}
	}
	userID := strconv.FormatInt(reply.FromMsg.UserId, 10)
	if reply.FromMsg.UserId == 0 {
		userID = ""
	}
	groupID := strconv.FormatInt(reply.FromMsg.GroupInfo.GroupId, 10)
	if reply.FromMsg.GroupInfo.GroupId == 0 {
		groupID = ""
	}
	sendPkg := model.GenSendPkg(userID, groupID, reply.ReplyMsg, false, false)
	sendPkgJson, err := json.Marshal(sendPkg)
	if err != nil {
		return err
	}
	for !am.Started() {
		time.Sleep(100 * time.Millisecond)
	}
	log.Default().Printf("\033[32m↑\033[0m:%s", string(sendPkgJson))
	if err = am.botConn.WriteMessage(websocket.TextMessage, sendPkgJson); err != nil {
		return err
	}
	return nil
}

func (am *actionManager) SendForward(reply *model.Reply) error {
	am.sendMtx.Lock()
	defer am.sendMtx.Unlock()
	userID := strconv.FormatInt(reply.FromMsg.UserId, 10)
	if reply.FromMsg.UserId == 0 {
		userID = ""
	}
	groupID := strconv.FormatInt(reply.FromMsg.GroupInfo.GroupId, 10)
	if reply.FromMsg.GroupInfo.GroupId == 0 {
		groupID = ""
	}
	sendPkg := model.GenSendPkg(userID, groupID, reply.ReplyMsg, false, true)
	sendPkgJson, err := json.Marshal(sendPkg)
	if err != nil {
		return err
	}
	log.Default().Printf("\033[32m↑\033[0m(forward):%s", string(sendPkgJson))
	if err = am.botConn.WriteMessage(websocket.TextMessage, sendPkgJson); err != nil {
		return err
	}
	return nil
}

func (am *actionManager) DrawbackMsg(msgId int32) error {
	withDrawPkg := model.GenDrawbackPkg(msgId)
	withDrawPkgJson, err := json.Marshal(withDrawPkg)
	if err != nil {
		return err
	}
	if err = am.botConn.WriteMessage(websocket.TextMessage, withDrawPkgJson); err != nil {
		return err
	}
	return nil
}
