namespace Server.Core
{
    public struct ObjectRef<T> where T : class,IReference
    {
        private readonly long ReferenceId;
        
        private T self;

        private ObjectRef(T t)
        {
            if (t == null)
            {
                this.ReferenceId = 0;
                this.self = null;
                return;
            }

            this.ReferenceId = t.ReferenceId;
            this.self = t;
        }

        private T UnWarp
        {
            get
            {
                if (this.self == null)
                {
                    return null;
                }

                if (this.self.ReferenceId != this.ReferenceId)
                {
                    this.self = null;
                }

                return this.self;
            }
        }

        public static implicit operator ObjectRef<T>(T t)
        {
            return new ObjectRef<T>(t);
        }
        
        public static implicit operator T(ObjectRef<T> t)
        {
            return t.UnWarp;
        }
    }
}