using System;
using System.Drawing;
using System.Drawing.Imaging;
using OpenTK.Graphics.OpenGL;

namespace %%%PROJECT_ID%%%
{
	public static class GlUtil
	{
		public static int ForceLoadTexture(Bitmap bitmap)
		{
			bitmap = NormalizeBitmap(bitmap);
			int width = bitmap.Width;
			int height = bitmap.Height;
			int textureId;

			Rectangle rectangle = new Rectangle(0, 0, width, height);
			BitmapData bmpData = bitmap.LockBits(
				rectangle, ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);

			GL.GenTextures(1, out textureId);
			GL.BindTexture(TextureTarget.Texture2D, textureId);
			GL.TexImage2D(
				TextureTarget.Texture2D,
				0,
				PixelInternalFormat.Rgba,
				width, height, 0,
				OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte,
				bmpData.Scan0);

			bitmap.UnlockBits(bmpData);

			GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Nearest);
			GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Nearest);

			return textureId;
		}

		private static readonly Point TOP_LEFT = new Point(0, 0);
		private static Bitmap NormalizeBitmap(Bitmap bitmap)
		{
			int oldWidth = bitmap.Width;
			int oldHeight = bitmap.Height;

			int newWidth = CrayonWrapper.v_nextPowerOf2(oldWidth);
			int newHeight = CrayonWrapper.v_nextPowerOf2(oldHeight);

			if (newWidth == oldWidth &&
				newHeight == oldHeight &&
				bitmap.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb)
			{
				return bitmap;
			}

			Bitmap targetBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
			targetBmp.SetResolution(bitmap.HorizontalResolution, bitmap.VerticalResolution);
			System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(targetBmp);
			g.DrawImage(bitmap, TOP_LEFT);
			return targetBmp;
		}

		private static int maxTextureSize = -1;
		public static int MaxTextureSize
		{
			get
			{
				if (maxTextureSize == -1)
				{
					/*
					// TODO: figure out why this isn't working...
					int value;
					OpenTK.Graphics.OpenGL.GL.GetInteger(OpenTK.Graphics.OpenGL.GetPName.MaxTextureSize, out value);
					maxTextureSize = value;
					//*/
					maxTextureSize = 1024 * 16;
				}
				return maxTextureSize;
			}
		}
	}
}
