package action

import (
	"encoding/json"
	"fmt"

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

func init() {
}

var ActionManager = actionManager{}

type actionManager struct {
	botConn *websocket.Conn
}

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 {
	if reply.ReferOriginMsg {
		replyMsg := message.ReplyMessage{
			Type: "reply",
			Data: message.ReplyMessageData{
				ID: int(reply.FromMsg.OriginMsgId),
			},
		}
		reply.ReplyMsg = fmt.Sprintf("%s%s", replyMsg.ToCQString(), reply.ReplyMsg)
	}
	sendPkg := model.GenSendPkg(reply.FromMsg.UserId, reply.FromMsg.GroupInfo.GroupId, reply.ReplyMsg, false)
	sendPkgJson, err := json.Marshal(sendPkg)
	if err != nil {
		return err
	}
	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
}

func (am *actionManager) GetGroupMemberList(groupId int64) ([]int64, error) {
	askGroupMemberListPkg := model.GenGetGroupMemberListPkg(groupId)
	askGroupMemberListPkgJson, err := json.Marshal(askGroupMemberListPkg)
	if err != nil {
		return nil, err
	}
	if err = am.botConn.WriteMessage(websocket.TextMessage, askGroupMemberListPkgJson); err != nil {
		return nil, err
	}
	return nil, nil //todo
}
