use super::*;
use super::errors::*;

use std::mem::uninitialized;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct ProgramId(u32);

impl From<ProgramId> for u32 {
    fn from(program_id: ProgramId) -> Self {
        program_id.0
    }
}

pub unsafe fn create_program() -> ProgramId {
    ProgramId(gl::CreateProgram())
}

pub unsafe fn delete_program(id: ProgramId) {
    gl::DeleteProgram(id.into());
}

pub unsafe fn attach_shader(program_id: ProgramId, shader_id: ShaderId) -> Result<()> {
    gl::AttachShader(program_id.into(), shader_id.into());
    get_error(())
}

pub unsafe fn detach_shader(program_id: ProgramId, shader_id: ShaderId) -> Result<()> {
    gl::DetachShader(program_id.into(), shader_id.into());
    get_error(())
}

pub unsafe fn link_program(id: ProgramId) -> Result<()> {
    gl::LinkProgram(id.into());
    get_error(())
}

pub unsafe fn get_program(id: ProgramId, parameter: ShaderProgramParameter) -> Result<i32> {
    let mut value: gl::types::GLint = uninitialized();

    gl::GetProgramiv(id.into(), parameter.into(), &mut value);

    get_error(value)
}

pub unsafe fn get_program_info_log(id: ProgramId) -> Result<String> {
    let mut error_log_size: gl::types::GLint =
        get_program(id.into(), ShaderProgramParameter::InfoLogLength)
            .chain_err(|| "Could not get log length")?;

    let mut error_log: Vec<u8> = Vec::with_capacity(error_log_size as usize);
    gl::GetProgramInfoLog(
        id.into(),
        error_log_size,
        &mut error_log_size,
        error_log.as_mut_ptr() as *mut gl::types::GLchar,
    );

    error_log.set_len(error_log_size as usize);
    let string = match String::from_utf8(error_log) {
        Ok(s) => s,
        Err(_) => bail!("Could not convert log"),
    };

    Ok(string)
}

pub unsafe fn use_program(id: ProgramId) -> Result<()> {
    gl::UseProgram(id.into());

    get_error(())
}
