using System;
using System.IO;
using System.Text;

namespace SharpQuake
{
	internal class LoadMenu : MenuBase
	{
		public override void Show()
		{
			base.Show();
			this.ScanSaves();
		}

		public override void KeyEvent(int key)
		{
			if (key != 13)
			{
				if (key != 27)
				{
					switch (key)
					{
					case 128:
					case 130:
						snd.LocalSound("misc/menu1.wav");
						this._Cursor--;
						if (this._Cursor < 0)
						{
							this._Cursor = 11;
							return;
						}
						break;
					case 129:
					case 131:
						snd.LocalSound("misc/menu1.wav");
						this._Cursor++;
						if (this._Cursor >= 12)
						{
							this._Cursor = 0;
						}
						break;
					default:
						return;
					}
					return;
				}
				MenuBase.SinglePlayerMenu.Show();
				return;
			}
			else
			{
				snd.LocalSound("misc/menu2.wav");
				if (!this._Loadable[this._Cursor])
				{
					return;
				}
				MenuBase.Hide();
				Scr.BeginLoadingPlaque();
				Cbuf.AddText(string.Format("load s{0}\n", this._Cursor));
				return;
			}
		}

		public override void Draw()
		{
			glpic_t glpic_t = Drawer.CachePic("gfx/p_load.lmp");
			menu.DrawPic((320 - glpic_t.width) / 2, 4, glpic_t);
			for (int i = 0; i < 12; i++)
			{
				menu.Print(16, 32 + 8 * i, this._FileNames[i]);
			}
			menu.DrawCharacter(8, 32 + this._Cursor * 8, 12 + ((int)(host.RealTime * 4.0) & 1));
		}

		protected void ScanSaves()
		{
			for (int i = 0; i < 12; i++)
			{
				this._FileNames[i] = "--- UNUSED SLOT ---";
				this._Loadable[i] = false;
				FileStream fileStream = sys.FileOpenRead(string.Format("{0}/s{1}.sav", common.GameDir, i));
				if (fileStream != null)
				{
					using (StreamReader streamReader = new StreamReader(fileStream, Encoding.ASCII))
					{
						if (streamReader.ReadLine() != null)
						{
							string text = streamReader.ReadLine();
							if (text != null)
							{
								text = text.TrimEnd(new char[]
								{
									'\0',
									'_'
								}).Replace('_', ' ');
								if (!string.IsNullOrEmpty(text))
								{
									this._FileNames[i] = text;
									this._Loadable[i] = true;
								}
							}
						}
					}
				}
			}
		}

		public LoadMenu()
		{
			this._FileNames = new string[12];
			this._Loadable = new bool[12];
		}

		public const int MAX_SAVEGAMES = 12;

		protected string[] _FileNames;

		protected bool[] _Loadable;
	}
}
