using System;
using System.Collections.Generic;
using System.Linq;
using NBC.Scheduler;
using NBC.Async;
using NBC.Entitas;
using NBC.Event;
using NBC.IdFactory;
using NBC.Network;
using NBC.Network.Interface;
using NBC.Pool;

// ReSharper disable ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract
#pragma warning disable CS8601 // Possible null reference assignment.
#pragma warning disable CS8625 // Cannot convert null literal to non-nullable reference type.
#pragma warning disable CS8603 // Possible null reference return.
#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. Consider declaring as nullable.
#pragma warning disable CS8602 // Dereference of a possibly null reference.
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
namespace NBC
{
    /// <summary>
    /// 当Scene创建完成后发送的事件参数
    /// </summary>
    public struct OnCreateScene
    {
        /// <summary>
        /// 获取与事件关联的场景实体。
        /// </summary>
        public readonly Scene Scene;

        /// <summary>
        /// 初始化一个新的 OnCreateScene 实例。
        /// </summary>
        /// <param name="scene"></param>
        public OnCreateScene(Scene scene)
        {
            Scene = scene;
        }
    }

    /// <summary>
    /// 表示一个场景实体，用于创建与管理特定的游戏场景信息。
    /// </summary>
    public partial class Scene : Entity
    {
        #region Members

        /// <summary>
        /// Scene的运行类型
        /// </summary>
        public SceneRuntimeType SceneRuntimeType { get; protected set; }

        /// <summary>
        /// 当前Scene的上下文
        /// </summary>
        public ThreadSynchronizationContext ThreadSynchronizationContext { get; internal set; }

        /// <summary>
        /// 当前Scene的下创建的Entity
        /// </summary>
        private readonly Dictionary<long, Entity> _entities = new Dictionary<long, Entity>();

        internal readonly Dictionary<Type, Func<IPool>> TypeInstance = new Dictionary<Type, Func<IPool>>();

        #endregion

        #region IdFactory

        /// <summary>
        /// Entity实体Id的生成器
        /// </summary>
        public IEntityIdFactory EntityIdFactory { get; protected set; }

        /// <summary>
        /// Entity实体RuntimeId的生成器
        /// </summary>
        public IRuntimeIdFactory RuntimeIdFactory { get; protected set; }

        #endregion

        #region Pool

        internal EntityPool EntityPool;
        internal EntityListPool<Entity> EntityListPool;
        internal EntitySortedDictionaryPool<long, Entity> EntitySortedDictionaryPool;

        #endregion

        #region Component

        /// <summary>
        /// Scene下的任务调度器系统组件
        /// </summary>
        public TimerComponent TimerComponent { get; internal set; }

        /// <summary>
        /// Scene下的事件系统组件
        /// </summary>
        public EventComponent EventComponent { get; internal set; }

        /// <summary>
        /// Scene下的ESC系统组件
        /// </summary>
        public EntityComponent EntityComponent { get; internal set; }

        /// <summary>
        /// Scene下的网络消息对象池组件
        /// </summary>
        public MessagePoolComponent MessagePoolComponent { get; internal set; }

        /// <summary>
        /// Scene下的协程锁组件
        /// </summary>
        public CoroutineLockComponent CoroutineLockComponent { get; internal set; }

        /// <summary>
        /// Scene下的网络消息派发组件
        /// </summary>
        internal MessageDispatcherComponent MessageDispatcherComponent { get; set; }

        #endregion

        #region Initialize

        private async FTask Initialize()
        {
            EntityPool = new EntityPool();
            EntityListPool = new EntityListPool<Entity>();
            EntitySortedDictionaryPool = new EntitySortedDictionaryPool<long, Entity>();
            SceneUpdate = EntityComponent = await Create<EntityComponent>(this, false, false).Initialize();
            MessagePoolComponent = Create<MessagePoolComponent>(this, false, true);
            EventComponent = await Create<EventComponent>(this, false, true).Initialize();
            TimerComponent = Create<TimerComponent>(this, false, true).Initialize();
            CoroutineLockComponent = Create<CoroutineLockComponent>(this, false, true).Initialize();
            MessageDispatcherComponent = await Create<MessageDispatcherComponent>(this, false, true).Initialize();
        }

        /// <summary>
        /// Scene销毁方法，执行了该方法会把当前Scene下的所有实体都销毁掉。
        /// </summary>
        public override void Dispose()
        {
            if (IsDisposed)
            {
                return;
            }

            base.Dispose();
            _entities.Remove(RuntimeId);

            switch (SceneRuntimeType)
            {
                case SceneRuntimeType.Root:
                {
                    _entities.Remove(EntityComponent.RuntimeId);

                    foreach (var (runtimeId, entity) in _entities.ToList())
                    {
                        if (runtimeId != entity.RuntimeId)
                        {
                            continue;
                        }

                        entity.Dispose();
                    }

                    _entities.Clear();
                    _unityWorldId--;
                    _unitySceneId--;
                    TypeInstance.Clear();
                    EntityComponent.Dispose();
                    EntityPool.Dispose();
                    EntityListPool.Dispose();
                    EntitySortedDictionaryPool.Dispose();
                    break;
                }
                case SceneRuntimeType.SubScene:
                {
                    break;
                }
                default:
                {
                    Log.Error(
                        $"SceneRuntimeType: {SceneRuntimeType} The unsupported SceneRuntimeType of the Scene executed Dispose.");
                    break;
                }
            }

            SceneUpdate = null;
            EntityIdFactory = null;
            RuntimeIdFactory = null;

            EntityPool = null;
            EntityListPool = null;
            EntitySortedDictionaryPool = null;
            EntityComponent = null;
            TimerComponent = null;
            EventComponent = null;
            MessagePoolComponent = null;
            CoroutineLockComponent = null;
            MessageDispatcherComponent = null;
            Session = null;
            UnityNetwork = null;
            ThreadSynchronizationContext = null;
            SceneRuntimeType = SceneRuntimeType.None;
        }

        #endregion

        internal ISceneUpdate SceneUpdate { get; set; }

        internal void Update()
        {
            try
            {
                SceneUpdate.Update();
            }
            catch (Exception e)
            {
                Log.Error(e);
            }
        }

        #region Create

        private static uint _unitySceneId = 0;
        private static byte _unityWorldId = 0;
        public Session Session { get; private set; }
        private AClientNetwork UnityNetwork { get; set; }

        /// <summary>
        /// 创建一个Unity的Scene，注意:该方法只能在主线程下使用。
        /// </summary>
        /// <param name="sceneRuntimeMode">选择Scene的运行方式</param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public static async FTask<Scene> Create(string sceneRuntimeMode = SceneRuntimeMode.MainThread)
        {
            var world = ++_unityWorldId;

            if (world > byte.MaxValue - 1)
            {
                throw new Exception($"World ID ({world}) exceeds the maximum allowed value of 255.");
            }

            var sceneId = (uint)(++_unitySceneId + world * 1000);

            if (sceneId > 255255)
            {
                throw new Exception($"Scene ID ({sceneId}) exceeds the maximum allowed value of 255255.");
            }

            var scene = new Scene();
            scene.Scene = scene;
            scene.Parent = scene;
            scene.Type = typeof(Scene);
            scene.SceneRuntimeType = SceneRuntimeType.Root;
            scene.EntityIdFactory = IdFactoryHelper.EntityIdFactory(sceneId, world);
            scene.RuntimeIdFactory = IdFactoryHelper.RuntimeIdFactory(0, sceneId, world);
            scene.Id = IdFactoryHelper.EntityId(0, sceneId, world, 0);
            scene.RuntimeId = IdFactoryHelper.RuntimeId(0, sceneId, world, 0);
            scene.AddEntity(scene);
            await SetScheduler(scene, sceneRuntimeMode);
            scene.ThreadSynchronizationContext.Post(() =>
            {
                scene.EventComponent.PublishAsync(new OnCreateScene(scene)).Coroutine();
            });
            return scene;
        }

        public Session Connect(string remoteAddress, NetworkProtocolType networkProtocolType, Action onConnectComplete,
            Action onConnectFail, Action onConnectDisconnect, bool isHttps, int connectTimeout = 5000)
        {
            UnityNetwork?.Dispose();
            UnityNetwork = NetworkProtocolFactory.CreateClient(this, networkProtocolType, NetworkTarget.Outer);
            Session = UnityNetwork.Connect(remoteAddress, onConnectComplete, onConnectFail, onConnectDisconnect,
                isHttps, connectTimeout);
            return Session;
        }

        private static async FTask SetScheduler(Scene scene, string sceneRuntimeMode)
        {
            switch (sceneRuntimeMode)
            {
                case "MainThread":
                {
                    scene.ThreadSynchronizationContext = ThreadScheduler.MainScheduler.ThreadSynchronizationContext;
                    scene.SceneUpdate = new EmptySceneUpdate();
                    ThreadScheduler.AddMainScheduler(scene);
                    await scene.Initialize();
                    break;
                }
                case "MultiThread":
                {
                    scene.ThreadSynchronizationContext = new ThreadSynchronizationContext();
                    scene.SceneUpdate = new EmptySceneUpdate();
                    ThreadScheduler.AddToMultiThreadScheduler(scene);
                    await scene.Initialize();
                    break;
                }
                case "ThreadPool":
                {
                    scene.ThreadSynchronizationContext = new ThreadSynchronizationContext();
                    scene.SceneUpdate = new EmptySceneUpdate();
                    ThreadScheduler.AddToThreadPoolScheduler(scene);
                    await scene.Initialize();
                    break;
                }
            }
        }

        #endregion

        #region Entities

        /// <summary>
        /// 添加一个实体到当前Scene下
        /// </summary>
        /// <param name="entity">实体实例</param>
        public virtual void AddEntity(Entity entity)
        {
            _entities.Add(entity.RuntimeId, entity);
        }

        /// <summary>
        /// 根据RunTimeId查询一个实体
        /// </summary>
        /// <param name="runTimeId">实体的RunTimeId</param>
        /// <returns>返回的实体</returns>
        public virtual Entity GetEntity(long runTimeId)
        {
            return _entities.TryGetValue(runTimeId, out var entity) ? entity : null;
        }

        /// <summary>
        /// 根据RunTimeId查询一个实体
        /// </summary>
        /// <param name="runTimeId">实体的RunTimeId</param>
        /// <param name="entity">实体实例</param>
        /// <returns>返回一个bool值来提示是否查找到这个实体</returns>
        public virtual bool TryGetEntity(long runTimeId, out Entity entity)
        {
            return _entities.TryGetValue(runTimeId, out entity);
        }

        /// <summary>
        /// 根据RunTimeId查询一个实体
        /// </summary>
        /// <param name="runTimeId">实体的RunTimeId</param>
        /// <typeparam name="T">要查询实体的泛型类型</typeparam>
        /// <returns>返回的实体</returns>
        public virtual T GetEntity<T>(long runTimeId) where T : Entity
        {
            return _entities.TryGetValue(runTimeId, out var entity) ? (T)entity : null;
        }

        /// <summary>
        /// 根据RunTimeId查询一个实体
        /// </summary>
        /// <param name="runTimeId">实体的RunTimeId</param>
        /// <param name="entity">实体实例</param>
        /// <typeparam name="T">要查询实体的泛型类型</typeparam>
        /// <returns>返回一个bool值来提示是否查找到这个实体</returns>
        public virtual bool TryGetEntity<T>(long runTimeId, out T entity) where T : Entity
        {
            if (_entities.TryGetValue(runTimeId, out var getEntity))
            {
                entity = (T)getEntity;
                return true;
            }

            entity = null;
            return false;
        }

        /// <summary>
        /// 删除一个实体，仅是删除不会指定实体的销毁方法
        /// </summary>
        /// <param name="runTimeId">实体的RunTimeId</param>
        /// <returns>返回一个bool值来提示是否删除了这个实体</returns>
        public virtual bool RemoveEntity(long runTimeId)
        {
            return _entities.Remove(runTimeId);
        }

        /// <summary>
        /// 删除一个实体，仅是删除不会指定实体的销毁方法
        /// </summary>
        /// <param name="entity">实体实例</param>
        /// <returns>返回一个bool值来提示是否删除了这个实体</returns>
        public virtual bool RemoveEntity(Entity entity)
        {
            return _entities.Remove(entity.RuntimeId);
        }

        #endregion
    }
}