using System.Collections;
using System.IO;

namespace InABox.Core
{
    public interface IPackableList : IPackable, IList
    {
    }

    public class PackableList<T> : ObservableList<T>, IPackableList where T : BaseObject, IPackable, new()
    {
        public void Pack(BinaryWriter writer)
        {
            writer.Write(Count);
            foreach (var item in this)
                item.Pack(writer);
        }

        public void Unpack(BinaryReader reader)
        {
            var iCount = reader.ReadInt32();
            for (var i = 0; i < iCount; i++)
            {
                var item = new T();
                item.Unpack(reader);
                Add(item);
            }
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            var other = obj as PackableList<T>;
            if (other == null)
                return false;

            if (Count != other.Count) // Require equal count.
                return false;
            for (var i = 0; i < Count; i++)
            {
                var item1 = this[i];
                var item2 = other[i];
                if (item1 == null)
                {
                    if (item2 != null)
                        return false;
                }
                else if (!item1.Equals(item2))
                {
                    return false;
                }
            }

            return true;
        }
    }
}