package qznn

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

func (p *Game) Run(allReady bool, roomItem Room, issue string) {
	var err error

	p.SendStartMsg(roomItem)

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

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

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

	logrus.Info("Finish")
}

func (p *Game) SendStartMsg(roomItem Room) {
	p.locker.Lock()
	defer p.locker.Unlock()

	userIDList, err := p.getRoomUserIDList(roomItem.ID)
	if err != nil {
		logrus.Error(err)
		return
	}

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

		if userItem.Status != PlayerStatusReady {
			p.Leave(userID, false)
		}
	}

	//更新一下房间用户
	userIDList, err = p.getRoomUserIDList(roomItem.ID)
	if err != nil {
		logrus.Error(err)
		return
	}

	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,
			})
		}
	}
}
