package mc

import (
	"crypto/rand"
	"encoding/binary"
	"errors"
	"tg-mc/conf"
	"tg-mc/models"
	su "tg-mc/services/utils"
	"tg-mc/utils"
	"time"

	"github.com/Tnze/go-mc/chat"
	"github.com/Tnze/go-mc/data/packetid"
	"github.com/Tnze/go-mc/net/packet"
	"github.com/sirupsen/logrus"
)

func GetJoinedPlayer(m chat.Message) (userName string, err error) {
	if m.Translate != "multiplayer.player.joined" && len(m.With) == 0 {
		return "", errors.New(ErrNotJoined)
	}
	userName = m.With[0].Text
	return
}

func GetLeftPlayer(m chat.Message) (userName string, err error) {
	if m.Translate != "multiplayer.player.left" && len(m.With) == 0 {
		return "", errors.New(ErrNotJoined)
	}
	userName = m.With[0].Text
	return
}

func HandleJoinGame(userName string) {

	u, err := models.GetUserByMCName(userName)
	if err != nil {
		logrus.Error("get user name error: ", err)
	}
	time.Sleep(3 * time.Second)

	switch u.Status {
	case StatusNormal:
		SendMsgToPlayer("欢迎回来！", userName)
	case StatusPending:
		SendMsgToPlayer("你还没有绑定 Telegram 哦, 5秒后你将会被踢出。请在群组中发送 /bind <你的 MC 用户名> 进行绑定。", userName)
		time.Sleep(5 * time.Second)
		kickPlayer(userName)
	case StatusBanned:
		SendMsgToPlayer("你已被封禁，如有疑问请联系管理员。", userName)
	default:
		SendMsgToPlayer("未知错误，请联系管理员，你将被踢出", userName)
		time.Sleep(3 * time.Second)
		kickPlayer(userName)
	}
}

func sendCommand(cmd string) error {
	var salt int64
	if err := binary.Read(rand.Reader, binary.BigEndian, &salt); err != nil {
		return err
	}

	err := conf.Client.Conn.WritePacket(packet.Marshal(
		packetid.ServerboundChatCommand,
		packet.String(cmd),
		packet.Long(time.Now().UnixMilli()),
		packet.Long(salt),
		packet.VarInt(0), // signature
		packet.VarInt(0),
		packet.NewFixedBitSet(20),
	))
	return err
}

func kickPlayer(userName string) error {
	err := sendCommand("kick " + userName)
	return err
}

func CronKick() {
	utils.CronStart(func() {
		users := su.GetAlivePlayerList()
		for _, u := range users {
			kickPlayer(u)
		}
	})
}
