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

use raw::{create_buffer, named_buffer_storage, delete_buffer, BufferId, BufferData,
          BufferMutability};

#[derive(Debug)]
pub struct ImmutableBuffer {
    id: BufferId,
}

impl ImmutableBuffer {
    /// Creates new buffer and copies `data` to its memory on GPU
    ///
    /// # Errors
    /// - BufferCreationError(GL_OUT_OF_MEMORY) - if the buffer cannot be created
    ///
    pub fn new<T>(data: &[T]) -> Result<ImmutableBuffer> {
        let id = create_buffer();

        unsafe {
            named_buffer_storage(
                id,
                BufferData::Data(data),
                BufferMutability::Immutable,
                None,
            ).chain_err(|| ErrorKind::BufferCreationError)?;
        }

        Ok(ImmutableBuffer { id: id })
    }
}

impl Buffer for ImmutableBuffer {
    fn get_id(&self) -> BufferId {
        self.id
    }
}

impl Drop for ImmutableBuffer {
    fn drop(&mut self) {
        unsafe {
            delete_buffer(self.id);
        }
    }
}
