using System;

namespace Decal.Filters;

public abstract class IdNameTable<EntryType> where EntryType : IIdNameTableEntry
{
	private int mCount;

	private EntryType[] mTable;

	public EntryType this[int index]
	{
		get
		{
			if (index >= 0 && index < mCount)
			{
				return mTable[index];
			}
			return default(EntryType);
		}
	}

	public int Length => mCount;

	public event EventHandler Update;

	internal abstract bool LoadFrom(byte[] data);

	internal bool UpdateFrom(byte[] data)
	{
		bool num = LoadFrom(data);
		if (num)
		{
			this.Update(this, null);
		}
		return num;
	}

	protected void InitializeTable(int n)
	{
		mCount = 0;
		mTable = (EntryType[])Array.CreateInstance(typeof(EntryType), n);
	}

	protected void Add(EntryType entry)
	{
		if (mCount < mTable.Length)
		{
			int num = mCount++;
			while (num > 0 && mTable[num - 1].Id > entry.Id)
			{
				mTable[num] = mTable[num - 1];
				num--;
			}
			mTable[num] = entry;
		}
	}

	public int IndexFromId(int id)
	{
		int num = 0;
		int num2 = mCount - 1;
		while (num <= num2)
		{
			int num3 = (num2 - num >> 1) + num;
			int id2 = mTable[num3].Id;
			if (id == id2)
			{
				return num3;
			}
			if (id < id2)
			{
				num2 = num3 - 1;
			}
			else
			{
				num = num3 + 1;
			}
		}
		return -1;
	}

	public int IndexFromName(string name)
	{
		for (int i = 0; i < mCount; i++)
		{
			if (string.Compare(mTable[i].Name, name, ignoreCase: true) == 0)
			{
				return i;
			}
		}
		return -1;
	}

	public EntryType GetById(int id)
	{
		return this[IndexFromId(id)];
	}

	public EntryType GetByName(string name)
	{
		return this[IndexFromName(name)];
	}
}
