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

namespace pcd_g1
{
	abstract class ScrollableStage : Stage
	{
		public ScrollableStage() : base()
		{
			ScrollX = 0; ScrollY = 0; ScrollRangeX = 0; ScrollRangeY = 0;
			mainCharacterX = 0; mainCharacterY = 0;
			Command.OnScrollStageCommandCalled += StageCommand_Scroll;
		}

		protected int ScrollX { get; set; }
		protected int ScrollY { get; set; }
		protected int ScrollRangeX { get; set; }
		protected int ScrollRangeY { get; set; }

		int mainCharacterX, mainCharacterY;
		private void StageCommand_Scroll(int x, int y)
		{
			mainCharacterX = x;
			mainCharacterY = y;
		}

		private const int SCROLL_LOCATION_MAX = 150;

		public override void Update(int keyStatus)
		{
			var records = new List<collidedRecord>();
			int width = 640;
			int margin = 256;

			//全項目のUpdate
			int vx, vy;
			foreach (var item in stageObjects)
			{
				if (item is MainCharacterStageObject || item is CommandableItemStageObject ||
					item is SwimmingBabbleCharacterStageObject || item is SwimmingMainCharacterStageObject ||
					item.X + item.Width >= ScrollX - margin && item.X <= ScrollX + width + margin)
				{
					item.Update(keyStatus, out vx, out vy);
					records.AddRange(
						move(item, vx, vy));
					if (item.Y > ScrollRangeY + 3000)
					{
						item.SignalProc(SignalType.SIGKILL, 0, 0);
					}
				}
			}

			base.Update(keyStatus, records, ScrollRangeY + 3000);
		}

		public override void Draw(Graphics g, int width, int height)
		{
			double goalX = mainCharacterX - width / 2;
			double goalY = mainCharacterY - height / 2;

			ScrollX += (int)((goalX - ScrollX) * 0.05);
			ScrollY += (int)((goalY - ScrollY) * 0.05);

			if (ScrollX > goalX + SCROLL_LOCATION_MAX) ScrollX = (int)goalX + SCROLL_LOCATION_MAX;
			if (ScrollX < goalX - SCROLL_LOCATION_MAX) ScrollX = (int)goalX - SCROLL_LOCATION_MAX;
			if (ScrollY > goalY + SCROLL_LOCATION_MAX) ScrollY = (int)goalY + SCROLL_LOCATION_MAX;
			if (ScrollY < goalY - SCROLL_LOCATION_MAX) ScrollY = (int)goalY - SCROLL_LOCATION_MAX;

			if (ScrollX < 0) ScrollX = 0;
			if (ScrollY < 0) ScrollY = 0;
			if (ScrollX > ScrollRangeX - width) ScrollX = ScrollRangeX - width;
			if (ScrollY > ScrollRangeY - height) ScrollY = ScrollRangeY - height;

			//stageObjectsの描画
			foreach (IStageObject item in Items)
			{
				if (item.X + item.Width >= ScrollX && item.Y + item.Height >= ScrollY &&
					item.X <= ScrollX + width && item.Y <= ScrollY + height)
				{
					g.ResetTransform();
					g.TranslateTransform((float)item.X - ScrollX, (float)item.Y - ScrollY);
					item.Draw(g, item.Width, item.Height);
				}
			}

		}

	}
}
