using System;

using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Drawing;

using Icarus.Graphics.Animation;

namespace Icarus.Renderer.Animation
{
	/// <summary>
	/// This is a frame that utilizes DirectDraw for rendering stuff.
	/// </summary>
	public class DDFrame : AbstractFrame
	{
//		/// <summary>
//		/// The DD surface containing the frame image.
//		/// </summary>
//		private Surface m_FrameImage;
//
//		/// <summary>
//		/// Creates a surface from the image passed in.
//		/// </summary>
//		public override bool initializeFromBitmap(Bitmap image) 
//		{
//			m_FrameImage = Surface.FromBitmap(
//				Direct3DSettings.Instance.RenderingDevice,
//				image,
//				Pool.SystemMemory);
//
//			return true;
//		}
//
//		/// <summary>
//		/// Returns the image of this frame.
//		/// </summary>
//		public override Bitmap getFrameImage()
//		{
//			GraphicsStream stream = SurfaceLoader.SaveToStream(ImageFileFormat.Bmp, m_FrameImage);
//
//			return (Bitmap) Bitmap.FromStream(stream);
//		}
//
//		/// <summary>
//		/// Renders this frame into a sprite.
//		/// </summary>
//		public override void Render(Point coords, IRenderParameters param)
//		{
//			DDRenderParameters p = (DDRenderParameters) param;
//			Device d = p.TargetSurface.Device;
//
//			Point pnt = new Point(
//				coords.X - this.getAnchorPoint().X,
//				coords.Y - this.getAnchorPoint().Y
//				);
//
//			d.UpdateSurface(m_FrameImage, p.TargetSurface, pnt);
//		}

		private Bitmap m_FrameImage;

        /// <summary>
        /// Initialize the frame from a Bitmap
        /// </summary>
        /// <param name="image">The image to load</param>
        /// <returns>true</returns>
		public override bool initializeFromBitmap(Bitmap image)
		{
			m_FrameImage = image;

			return true;
		}

        /// <summary>
        /// Return the Frame Image as a Bitmap
        /// </summary>
        /// <returns>The Frame Image</returns>
		public override Bitmap getFrameImage()
		{
			return m_FrameImage;
		}

		/// <summary>
		/// Renders this frame into a sprite.
		/// </summary>
		public override void Render(Rectangle coords, IRenderParameters param)
		{
			int x = coords.X - this.getAnchorPoint().X;
			int y = coords.Y - this.getAnchorPoint().Y;

			DDRenderParameters p = (DDRenderParameters) param;
			System.Drawing.Graphics g = p.TargetSurface.GetGraphics();

			if (coords.Size == Size.Empty)
			{
				g.DrawImageUnscaled(m_FrameImage, x, y);
			} 
			else
			{
				int width = Math.Min(m_FrameImage.Width, coords.Width);
				int height = Math.Min(m_FrameImage.Height, coords.Height);
				Rectangle src = new Rectangle(0, 0, width, height);

				g.DrawImage(m_FrameImage, x, y, src, GraphicsUnit.Pixel);
			}

			p.TargetSurface.ReleaseGraphics();
		}
	}
}
