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

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

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

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

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

        Ok(MutableBuffer { id: id })
    }

    /// Creates new empty buffer
    ///
    /// # Errors
    /// - BufferCreationError(GL_OUT_OF_MEMORY) - if the buffer cannot be created
    ///
    pub fn new_empty(size: usize) -> Result<MutableBuffer> {
        let id = create_buffer();

        unsafe {
            named_buffer_storage::<u8, Option<BufferMap>>(
                id,
                BufferData::Empty(size),
                BufferMutability::Mutable,
                None,
            ).chain_err(|| ErrorKind::BufferCreationError)?;
        }

        Ok(MutableBuffer { id: id })
    }

    /// Replaces part of memory with `data`
    ///
    /// # Errors
    /// - BufferSetSubDataError(GL_INVALID_VALUE) - if size of `data` + offset > buffer size
    ///
    pub fn set_sub_data<T>(&mut self, data: &[T], offset: isize) -> Result<()> {
        unsafe {
            named_buffer_sub_data(self.id, offset, data).chain_err(|| {
                ErrorKind::BufferSetSubDataError
            })?;
        }

        Ok(())
    }
}

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

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