using System;
using System.Text;
using SlatedGameToolkit.Framework.Exceptions;
using SlatedGameToolkit.Framework.Graphics.OpenGL;
using SlatedGameToolkit.Framework.Graphics.Window;

namespace SlatedGameToolkit.Framework.Graphics.Render.Shaders
{
    public class VertexShader : IShadeable
    {
        public GLContext GLContext {get; private set;}
        private bool disposed;

        public uint Handle { get; private set; }

        public VertexShader(string program, GLContext context = null) {
            this.GLContext = context ?? WindowContextsManager.CurrentGL;
            Handle = GLContext.CreateShader(ShaderType.VertexShader);
            GLContext.ShaderSource(Handle, 1, new string[] {program}, null);
            GLContext.CompileShader(Handle);
            int status;
            GLContext.GetShaderiv(Handle, ShaderParameterName.CompileStatus, out status);
            if ((OpenGL.Boolean)status == OpenGL.Boolean.False) {
                int logLength;
                GLContext.GetShaderiv(Handle, ShaderParameterName.InfoLogLength, out logLength);                
                byte[] logData = new byte[logLength];
                int byteCount;
                GLContext.GetShaderInfoLog(Handle, logLength, out byteCount, logData);
                throw new FrameworkUsageException(string.Format("Error compiling shader: {0}", Encoding.UTF8.GetString(logData)));
            }
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!disposed)
            {
                if (disposing)
                {
                }
                GLContext.DeleteShader(Handle);
                disposed = true;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        ~VertexShader() {
            Dispose(false);
        }
    }
}