using System;
using System.Numerics;

namespace ET.Server
{
    /// <summary>
    /// 向场景增加单位
    /// </summary>
    [MessageHandler(SceneType.Game)]
    public class C2G_AddUnitsToMapHandler: AMRpcHandler<C2G_AddUnitsToMap, G2C_AddUnitsToMap>
    {
        protected override async ETTask Run(Session session, C2G_AddUnitsToMap request, G2C_AddUnitsToMap response, Action reply)
        {
            if (session.DomainScene().SceneType != SceneType.Game)
            {
                Log.Debug($"Game 请求的Scene错误...SceneType={session.DomainScene().SceneType}");
                session.Dispose();
                return;
            }

            // 移除session自动超时组件
            session.RemoveComponent<SessionAcceptTimeoutComponent>();

            WNPlayer player = session.GetComponent<SessionPlayerComponent>().GetMyPlayer();
            if (player == null)
            {
                Log.Debug($"操作错误, player is null");
                response.Error = ErrorCode.ERR_OperationError;
                reply();
                return;
            }
            // 参数判断
            if (request.UnitId <= 0 || request.Force < 0 || request.Force > (int)AreaForce.FORCEB )
            {
                Log.Debug($"参数错误...unitId={request.UnitId}, force={request.Force}");
                response.Error = ErrorCode.ERR_ParameterError;
                reply();
                return;
            }

            // 临时openId
            // while (true)
            // {
            //     string _openId = (10000 + new Random().Next(99999999)).ToString();
            //     if (player.Map.GetUnitPlayerByOpenId(_openId) != null) continue;
            //     await player.Map.AddUnitPlayer(_openId, request.UnitId, request.Force, request.Flag, request.X, request.Y, GetRandomPlayerName(), GetRandomUrl());
            //     break;
            // }
            reply();
            await ETTask.CompletedTask;
        }

        private string GetRandomPlayerName()
        {
            string[] names =
            {
                "好人", "小新", "精钢侠", "带投大戈", "奥仔", "袄特门", "兔比斯", "张剑闯天牙", "窝耗帅", "大白"
            };

            var rand = new Random();
            var first = names[rand.Next(names.Length)];
            return first + rand.Next(99);
        }

        private string GetRandomUrl()
        {
            string[] url =
            {
                "https://pic1.zhimg.com/v2-3f475a4727cdff2c7289ce3c728a0e67_r.jpg",
                "https://img.zcool.cn/community/01cfd95d145660a8012051cdb52093.png@1280w_1l_2o_100sh.png",
                "https://pic4.zhimg.com/v2-ceb6cc092425322d0b4cab403cd403d7_r.jpg",
                "https://pic3.zhimg.com/50/v2-e1ad5394ae2d3b2dc9d04c1d7a63f0e6_hd.jpg",
                "https://pic1.zhimg.com/v2-9ee4a6f411b9a8ff076c38f1dcb03024_b.jpg"
            };
            var rand = new Random();
            return url[rand.Next(url.Length)];
        }
    }
}