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

namespace pcd_g1
{
	class CommandableItemStageObject : ItemStageObject
	{
		public enum CommandTiming
		{
			Touch,
			Flag,
			DownKey,
			Time,
			Now
		}

		public CommandableItemStageObject(int x, int y, Stage stg, string img = "") : base(x, y, stg)
		{
			if (img != "") image = ImageManager.Search(img);
			if (image != null)
			{
				Width = image.Width;
				Height = image.Height;
			}
		}

		private class aCommand
		{
			public CommandTiming timing;
			public IStoryboard cmd;
			public string arg;
			public bool enabled = true;
		}

		private List<aCommand> commandList = new List<aCommand>();

		public void AddCommand(CommandTiming timing, IStoryboard cmd, string arg = "")
		{
			commandList.Add(new aCommand() { arg = arg, timing = timing, cmd = cmd, enabled = timing == CommandTiming.Flag ? false : true });
		}

		long counter = 0;
		bool downKeyPushed = true;
		public override void Update(int keyStatus, out int vx, out int vy)
		{
			base.Update(keyStatus, out vx, out vy);

			if ((keyStatus & (int)MainForm.KEYBOARD.Down) == 0) downKeyPushed = false;

			foreach (var item in commandList)
			{
				if (item.enabled)
				{
					switch (item.timing)
					{
						case CommandTiming.Flag:
							if (StageManager.CurrentDataSet.GetInt(item.arg) > 0)
							{
								item.cmd.Run();
								item.enabled = false;
							}
							break;
						case CommandTiming.DownKey:
							if ((keyStatus & (int)MainForm.KEYBOARD.Down) != 0 && !downKeyPushed)
							{
								foreach (IStageObject q in owner.GetCollidedStageObjects(this))
								{
									if (q is MainCharacterStageObject)
									{
										item.cmd.Run();
										MainForm.form.ResetKey();
									}
								}
								downKeyPushed = true;

							}
							break;
						case CommandTiming.Time:
							if (counter > int.Parse(item.arg))
							{
								item.cmd.Run();
								item.enabled = false;
							}
							break;
						case CommandTiming.Now:
							if (counter == 0)
							{
								item.cmd.Run();
								item.enabled = false;
							}
							break;
					}
				}
				else if (item.timing == CommandTiming.Flag && StageManager.CurrentDataSet.GetInt(item.arg) <= 0)
				{
					item.enabled = true;
				}
			}
			counter++;
		}

		public override bool EventProc(EventType type, IStageObject sender, CollideDirection direction)
		{
			if ((type == EventType.BeTouched || type == EventType.Touched) && sender is MainCharacterStageObject)
			{
				commandList.Where((j, b) => j.timing == CommandTiming.Touch).ToList().ForEach((j) => j.cmd.Run());
			}
			
			return base.EventProc(type, sender, direction);
		}

	}
}
