using MongoDB.Bson.Serialization.Attributes;
using System;

namespace KYFramework
{
    [BsonIgnoreExtraElements]
    public abstract class Component : Object , IDisposable
    {
        [BsonIgnore]
        public long InstanceId { get; set; }


        [BsonIgnore]
        protected bool isFromPool;

        [BsonIgnore]
        public bool IsFromPool
        {
            get
            {
                return isFromPool;
            }
            set
            {
                isFromPool = value;
                if (!this.isFromPool) return;
                if(InstanceId == 0)
                    InstanceId = IdGenerater.GenerateInstanceId();
            }
        }

        [BsonIgnore]
        public bool IsDisposed
        {
            get
            {
                return this.InstanceId == 0;
            }
        }

        private Component parent;

        [BsonIgnore]
        public Component Parent
        {
            get
            {
                return this.parent;
            }
            set
            {
                parent = value;
            }
        }

      

        public T GetParent<T>() where T : Component
        {
            return this.Parent as T;
        }

        [BsonIgnore]
        public Entity Entity
        {
            get
            {
                return this.Parent as Entity;
            }
        }

        protected Component()
        {
            this.InstanceId = IdGenerater.GenerateInstanceId();
        }

        public virtual void Dispose()
        {
            if (this.IsDisposed)
            {
                return;
            }

            // 触发Destroy事件
            Game.EventSystem.Destroy(this);

            Game.EventSystem.Remove(this.InstanceId);

            this.InstanceId = 0;

            if (this.IsFromPool)
            {
                Game.ObjectPool.Recycle(this);
            }
            else
            {
         
            }
        }

        public override void EndInit()
        {
            Game.EventSystem.Deserialize(this);
        }

        public override string ToString()
        {
            return MongoHelper.ToJson(this);
        }
    }
}