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

namespace Nlgp1.StageEditor.Notifies
{
	public class ChipsetImage : IEnumerable<Image>
	{
		public const int NoneIndex = 0;
		public static readonly ChipsetImage None = new ChipsetImage();

		public static int ChipSize { get; set; }

		private string path;
		public string Path {
			get { return path; }
			set {
				path = value;
				Image = Image.FromFile(path);
			} 
		}

		private Image image;
		public Image Image {
			get { return image; }
			private set {
				image = value;
				SetImageList();
			}
		}

		public Image this[int index] {
			get {
				if (index < 0) return null;
				if (index >= imageList.Count) return null;
				return imageList[index];
			}
		}

		public int Count
		{
			get { return imageList.Count; }
		}

		private IList<Image> imageList;

		static ChipsetImage()
		{
			ChipsetImage.ChipSize = 32;
		}

		public ChipsetImage()
		{
			this.imageList = new List<Image>();
		}

		private void SetImageList()
		{
			this.imageList.Clear();
			var row = (int)Math.Ceiling((double)image.Height / ChipSize);
			var column = (int)Math.Ceiling((double)image.Width / ChipSize);

			for (int y = 0; y < row; y++)
			{
				for (int x = 0; x < column; x++)
				{
					var posX = x * ChipSize;
					var posY = y * ChipSize;
					var srcRect = new Rectangle(posX, posY, ChipSize, ChipSize);
					var dstRect = new Rectangle(0, 0, ChipSize, ChipSize);
					var bitmap = new Bitmap(ChipSize, ChipSize);
					var graphics = Graphics.FromImage(bitmap);
					graphics.DrawImage(image, dstRect, srcRect, GraphicsUnit.Pixel);

					imageList.Add(bitmap);
				}
			}
		}

		#region IEnumerable<Image> メンバ

		public IEnumerator<Image> GetEnumerator()
		{
			foreach (var image in imageList)
			{
				yield return image;

			}
		}

		#endregion

		#region IEnumerable メンバ

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
		{
			foreach (var image in imageList)
			{
				yield return image;

			}
		}

		#endregion
	}
}
