using System;

namespace SharpQuake
{
	internal class ServerListMenu : MenuBase
	{
		public override void Show()
		{
			base.Show();
			this._Cursor = 0;
			menu.ReturnOnError = false;
			menu.ReturnReason = string.Empty;
			this._Sorted = false;
		}

		public override void KeyEvent(int key)
		{
			if (key <= 27)
			{
				if (key != 13)
				{
					if (key != 27)
					{
						return;
					}
					MenuBase.LanConfigMenu.Show();
					return;
				}
				else
				{
					snd.LocalSound("misc/menu2.wav");
					menu.ReturnMenu = this;
					menu.ReturnOnError = true;
					this._Sorted = false;
					MenuBase.Hide();
					Cbuf.AddText(string.Format("connect \"{0}\"\n", net.HostCache[this._Cursor].cname));
				}
			}
			else
			{
				if (key == 32)
				{
					MenuBase.SearchMenu.Show();
					return;
				}
				switch (key)
				{
				case 128:
				case 130:
					snd.LocalSound("misc/menu1.wav");
					this._Cursor--;
					if (this._Cursor < 0)
					{
						this._Cursor = net.HostCacheCount - 1;
						return;
					}
					break;
				case 129:
				case 131:
					snd.LocalSound("misc/menu1.wav");
					this._Cursor++;
					if (this._Cursor >= net.HostCacheCount)
					{
						this._Cursor = 0;
						return;
					}
					break;
				default:
					return;
				}
			}
		}

		public override void Draw()
		{
			if (!this._Sorted)
			{
				if (net.HostCacheCount > 1)
				{
					Comparison<hostcache_t> comparison = (hostcache_t a, hostcache_t b) => string.Compare(a.cname, b.cname);
					Array.Sort<hostcache_t>(net.HostCache, comparison);
				}
				this._Sorted = true;
			}
			glpic_t glpic_t = Drawer.CachePic("gfx/p_multi.lmp");
			menu.DrawPic((320 - glpic_t.width) / 2, 4, glpic_t);
			for (int i = 0; i < net.HostCacheCount; i++)
			{
				hostcache_t hostcache_t = net.HostCache[i];
				string str;
				if (hostcache_t.maxusers > 0)
				{
					str = string.Format("{0,-15} {1,-15} {2:D2}/{3:D2}\n", new object[]
					{
						hostcache_t.name,
						hostcache_t.map,
						hostcache_t.users,
						hostcache_t.maxusers
					});
				}
				else
				{
					str = string.Format("{0,-15} {1,-15}\n", hostcache_t.name, hostcache_t.map);
				}
				menu.Print(16, 32 + 8 * i, str);
			}
			menu.DrawCharacter(0, 32 + this._Cursor * 8, 12 + ((int)(host.RealTime * 4.0) & 1));
			if (!string.IsNullOrEmpty(menu.ReturnReason))
			{
				menu.PrintWhite(16, 148, menu.ReturnReason);
			}
		}

		private bool _Sorted;
	}
}
