package qznn

import (
	"time"

	"github.com/sirupsen/logrus"
	"nn.daxia.dev/gameproto"
	"nn.daxia.dev/nxd"
)

func (p *Game) Run(allReady bool, roomItem Room, issue string) {
	//发送消息给界面，每个玩家，可以选择的倍数情况
	userIDList, err := p.getRoomUserIDList(roomItem.ID)
	if err != nil {
		logrus.Error(err)
		return
	}

	p.SendStartMsg(userIDList, roomItem)

	//选庄
	logrus.Info("WaitChooseMaster")
	err = p.WaitChooseMaster(roomItem)
	if err != nil {
		logrus.Error(err)
		return
	}

	//选倍数
	logrus.Info("WaitChooseMul")
	err = p.WaitChooseMul(roomItem)
	if err != nil {
		logrus.Error(err)
		return
	}

	//开奖
	logrus.Info("Wait open")
	err = p.WaitOpen(roomItem)
	if err != nil {
		logrus.Error(err)
		return
	}

	logrus.Info("Finish")

	//判断是否在线，不在线就退出了
	for _, userID := range userIDList {
		if UserIsOnline(uint(userID)) {
			continue
		}

		p.locker.Lock()
		{
			p.EventInfo(userID, "Run", "玩家离线，踢走")
		}
		p.locker.Unlock()

		p.Leave(userID)
	}
}

func (p *Game) SendStartMsg(userIDList []int32, roomItem Room) {
	p.locker.Lock()
	defer p.locker.Unlock()

	for _, userID := range userIDList {
		userItem, exists := p.PlayerMap[userID]
		if !exists {
			logrus.Error("not exist:", userID)
			continue
		}

		if userItem.Status == PlayerStatusReady {
			p.EventInfo(userID, "发送开始消息", "发送开始消息")

			nxd.SendMsgToUserK(uint32(userID), gameproto.NotifyTypeEnum_NotifyTypeStart, &gameproto.Start{
				RoomID:              uint32(roomItem.ID),
				ChooseMasterMulList: []uint32{0, 1, 2, 3},
				Issue:               roomItem.Issue,
				CardList:            GetNNCardListLimit(userItem.CardList, 3),
			})
		} else {
			p.EventInfo(userID, "发送开始消息", "通知开始,不参与")

			nxd.SendMsgToUserK(uint32(userID), gameproto.NotifyTypeEnum_NotifyTypeStart, &gameproto.Start{
				RoomID:              uint32(roomItem.ID),
				ChooseMasterMulList: []uint32{},
				Issue:               roomItem.Issue,
				CardList:            nil,
			})
		}
	}

	{
		roomItem.Status = RoomStatusChooseMaster
		roomItem.StatusStartTime = time.Now().Unix()
		p.RoomMap[roomItem.ID] = roomItem
	}
}
