using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace CaLib.User
{
	public class LimitedListBox : ListBox
	{
		protected int maxItemCount_ = 100;

		public void SetMax(int max)
		{
			maxItemCount_ = max;

			if (this.Items.Count > maxItemCount_)
			{
				RemoveOld(this.Items.Count - maxItemCount_);
			}
		}

		public virtual void InsertHead(object s)
		{
			try
			{
				this.BeginUpdate();

				this.Items.Insert(0, s);

				if (this.Items.Count > maxItemCount_)
				{
					RemoveOld(this.Items.Count - maxItemCount_);
				}
			}
			finally
			{
				this.EndUpdate();
			}
		}

		/// <summary>
		/// RemoveOldでアイテムが削除されるときに呼ばれます。
		/// </summary>
		/// <param name="s"></param>
		public virtual void OnRemoveItem(object s, int index)
		{ 
		}

		public void RemoveOld(int count)
		{
			for (int i = 0; i < count; i++)
			{
				int idx = Items.Count - 1;

				OnRemoveItem(Items[idx], idx);

				Items.RemoveAt(idx);
			}
		}

		/// <summary>
		/// 選択項目を削除する
		/// </summary>
		public void DeleteSelectedItem()
		{
			int index = this.SelectedIndex;
			if (index < 0)
				return;

			OnRemoveItem(Items[index], index);
			this.Items.RemoveAt(index);
		}

		public void Clear()
		{
			for (int index = 0; index < Items.Count; index++)
			{
				OnRemoveItem(Items[index], index);
			}
			this.Items.Clear();
		}

		public void RemoveLast()
		{
			if (this.Items.Count > 0)
			{
				OnRemoveItem(Items[0], 0);
				this.Items.RemoveAt(0);
			}
		}
	
	
	}
}
