using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoSellerNS
{
	public class ConcurrentList<T> : ConcurrentDictionary<int, T>, IList<T>
	{
		int m_Order = 0;

		public new T this[int index]
		{
			get
			{
				T value;
				if (ContainsKey(index) == true)
				{
					TryGetValue(index, out value);
					return value;
				}
				else
				{
					throw new IndexOutOfRangeException();
				}
			}

			set
			{
				AddOrUpdate(index, value, (k, v) => value);
			}
		}

		public bool IsReadOnly
		{
			get
			{
				return false;
			}
		}

		public void Add(T item)
		{
			TryAdd(m_Order++, item);
		}

		public bool Contains(T item)
		{
			return Contains(item);
		}

		public void CopyTo(T[] array, int arrayIndex)
		{
			throw new NotImplementedException();
		}

		public int IndexOf(T item)
		{
			foreach(var kv in this)
			{
				if (kv.Value.Equals(item))
					return kv.Key;
			}

			return -1;
		}

		public void Insert(int index, T item)
		{
			if(index < 0 || index >= m_Order)
				throw new ArgumentOutOfRangeException();

			this[index] = item;
		}

		public bool Remove(T item)
		{
			int index = IndexOf(item);
			if (index < 0)
				return false;

			this[index] = default(T);
			return true;
		}

		public void RemoveAt(int index)
		{
			if (index < 0 || ContainsKey(index) == false)
				throw new ArgumentOutOfRangeException();

			this[index] = default(T);
		}

		IEnumerator<T> IEnumerable<T>.GetEnumerator()
		{
			foreach(var kv in this)
			{
				yield return kv.Value;
			}
		}
	}
}
