using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;

namespace pcd_g1
{
	class SelectDialogWidghet : IWidghet
	{
		public int X { get; private set; }
		public int Y { get; private set; }
		public int Width { get; private set; }
		public int Height { get; private set; }
		public bool IsModal { get { return true; } }
		public bool IsSleeping { get { return false; } }
		public bool Visibility { get { return true; } }

		int result = -1;
		public int Result { get { return result; } }

		string[] messages;

		public SelectDialogWidghet(int x, int y, int width, int height, params string[] msgs)
		{
			back = new SolidBrush(Color.FromArgb(200, 255, 0, 0));
			front = new SolidBrush(Color.White);
			font = new Font("MS Gothic", 30);
			if (width != 0 && height != 0)
			{
				Width = 0;
				Height = 0;
				var b = new Bitmap(640,480);
				var g = Graphics.FromImage(b);
				foreach (var s in msgs)
				{
					SizeF w = g.MeasureString(s, font, 640);
					if (w.Width > Width) Width = (int)w.Width;
					Height += (int)w.Height;
				}
				g.Dispose();
				b.Dispose();

				X = x + width - Width;
				Y = y + height - Height;
			}
			else
			{
				Width = width;
				Height = height;
				X = x;
				Y = y;
			}
			
			messages = msgs;
			if (messages.Length > 0) activeIndex = 0;
			
			

		}

		int activeIndex = -1;
		bool keyPressed = true;
		public bool Update(int keyStatus)
		{
			if (activeIndex == -1) return true;
			if ((keyStatus & (int) MainForm.KEYBOARD.Z) != 0 && !keyPressed)
			{
				MainForm.PlayEffectSound("select");
				result = activeIndex;
				activeIndex = 0;
				MainForm.form.ResetKey();
				return true;
			}
			if ((keyStatus & (int)MainForm.KEYBOARD.Up) != 0 && !keyPressed)
			{
				MainForm.PlayEffectSound("focus");
				activeIndex--;
				if (activeIndex < 0) activeIndex = 0;
				keyPressed = true;
			}
			else if ((keyStatus & (int)MainForm.KEYBOARD.Down) != 0 && !keyPressed)
			{
				MainForm.PlayEffectSound("focus");
				activeIndex++;
				if (activeIndex >= messages.Length) activeIndex = messages.Length - 1;
				keyPressed = true;
			}
			else if(keyStatus == 0)
			{
				keyPressed = false;
			}
			return false;
		}

		Brush back, front;
		Font font;
		public void Draw(Graphics g, int width, int height)
		{
			int x = 10, y = 0, h;
			string m;
			g.FillRectangle(back, 0, 0, width, height);
			for (int i = 0; i < messages.Length; i++)
			{
				m = messages[i];
				h = (int) g.MeasureString(m, font).Height;
				if (y + h <= height)
				{
					g.DrawString(m, font, front, x, y);
					if (i == activeIndex)
					{
						g.FillRectangle(front, 0, y, x, h);
					}
				}
				y += h;
			}
		}
	}
}
