#include "GLShader.h"
#include <iostream>

using namespace std;

namespace jes
{
    GLShader::~GLShader()
    {
        if (m_id > 0)
        {
            glDeleteShader(m_id);
        }
    }

    bool GLShader::create(GLenum shader_type, const char *source, size_t size)
    {
        GLint status;

        m_id = glCreateShader(shader_type);
        if (m_id > 0)
        {
            GLint length = size;
            glShaderSource(m_id, 1, &source, &length);

            glCompileShader(m_id);

            glGetShaderiv(m_id, GL_COMPILE_STATUS, &status);
            if (status == GL_TRUE)
            {
                return true;
            }

            GLint log_length;
            cerr << "Error compiling ";
            switch (shader_type)
            {
                case GL_VERTEX_SHADER:
                    cerr << "vertex";
                    break;
                case GL_FRAGMENT_SHADER:
                    cerr << "fragment";
                    break;
            }
            cerr << " shader" << endl;
            glGetShaderiv(m_id, GL_INFO_LOG_LENGTH, &log_length);
            if (log_length > 0)
            {
                char * log = new char[log_length];
                glGetShaderInfoLog(m_id, log_length, &log_length, log);
                cerr << "Shader Log:" << endl << log << endl;
                delete[] log;
            }
            glDeleteShader(m_id);
        }
        return false;
    }

    bool GLShader::create(GLenum shader_type, PathRef path)
    {
        uint8_t * file;
        size_t size;
        if (!path->read(&file, &size))
            return false;
        if (size == 0u)
            return false;

        bool result = create(shader_type, (const char *)file, size);
        delete[] file;
        return result;
    }
}
