using System;
using Server;
using Server.Data;
using MrWu.Basic;
using MrWu.Debug;

namespace Game.Queue {

    /// <summary>
    /// 开放式排队
    /// 随时可以进入
    /// </summary>
    public class OpenQueue : IQueueControll {


        /// <summary>
        /// 所属厅
        /// </summary>
        public TingManager ting {
            get;
            private set;
        }

        /// <summary>
        /// 最小人数
        /// </summary>
        public int MinCnt {
            get {
                return ting.config.MinPlayerCnt;
            }
        }

        /// <summary>
        /// 最大人数
        /// </summary>
        public int MaxCnt {
            get {
                return ting.config.MaxPlayerCnt;
            }
        }

        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="ting"></param>
        public OpenQueue(TingManager ting) {
            this.ting = ting;
        }

        /// <summary>
        /// 添加玩家到排队
        /// </summary>
        /// <param name="pl">玩家</param>
        /// <param name="roomid">房间id</param>
        /// <param name="deskid">桌子id</param>
        /// <returns>是否添加成功</returns>
        public bool AddPlayer(PlayerDataAsyc pl, int roomid, int deskid = -1) {

            Desk desk = null;
            //指定桌子
            if (deskid >= 0) {
                if (ting.isExists(deskid))
                    desk = ting.desks[deskid];

                if (desk == null) {
                    Debug.Error("没有这个桌子!");
                    return false;
                }

                //满人了
                if ((desk.state & DeskState.Queue) == 0) { //不是排队中的桌子
                    if ((desk.state & DeskState.Idle) != 0)
                        ting.RemoveIdle(desk);
                    ting.AddQueueing(desk);
                }

                return ting.desks[deskid].AddPlayer(pl, roomid);
            }

            //随机桌子, 随机的桌子可以加入那么加入,不可加入就创建新桌加入
            if (ting.QueueCount > 0) {
                int idx = BaseFun.random.Next(0, ting.QueueCount);
                if (ting.queueing[deskid].AddPlayer(pl, roomid))
                    return true;
            }

            desk = ting.GetDesk(DeskState.Idle);
            if (desk == null) {
                Debug.Error("上桌子失败,没有空桌!!!");
                return false;
            }
            desk.Init();

            if (desk.AddPlayer(pl, roomid) && ((desk.state & DeskState.Queue) != 0)) { //上桌成功

                if ((desk.state & DeskState.Idle) > 0)
                    ting.RemoveIdle(desk);

                ting.AddQueueing(desk); //添加到排队列表
                return true;
            }
            return false;
        }

        /// <summary>
        /// 处理排队
        /// </summary>
        public void DoQueue() { }

        /// <summary>
        /// 某玩家取消排队
        /// </summary>
        /// <param name="pl">玩家</param>
        /// <returns>是否取消成功</returns>
        public bool Cancel(PlayerDataAsyc pl) { return true; }

    }
}
