//! The main database module, allowing to interface with LevelDB on
//! a key-value basis.
use crate::binding::*;

use self::error::Error;
use self::options::{Options, c_options};
use std::ffi::CString;

use std::path::Path;

use std::ptr;

use libc::c_char;

pub mod batch;
pub mod bytes;
pub mod cache;
pub mod compaction;
pub mod comparator;
pub mod error;
pub mod filter_policy;
pub mod iterator;
pub mod kv;
pub mod management;
pub mod options;
pub mod property;
pub mod slice;
pub mod snapshots;
pub mod statistics;
pub use slice::Slice;

#[allow(missing_docs)]
struct RawDB {
    ptr: *mut leveldb_t,
}

#[allow(missing_docs)]
impl Drop for RawDB {
    fn drop(&mut self) {
        unsafe {
            leveldb_close(self.ptr);
        }
    }
}

/// The main database object.
///
/// LevelDB databases are based on ordered keys. By default, LevelDB orders
/// by the binary value of the key. Additionally, a custom `Comparator` can
/// be passed when opening the database. This library ships with an Comparator
/// implementation for keys that are `Ord`.
///
/// Multiple Database objects can be kept around, as LevelDB synchronises
/// internally.
pub struct Database {
    database: RawDB,
    // these hold multiple references that are used by the leveldb library
    // and should survive as long as the database lives
    #[allow(dead_code)]
    options: Options,
}

unsafe impl Sync for Database {}
unsafe impl Send for Database {}

impl Database {
    fn new(database: *mut leveldb_t, options: Options) -> Database {
        Database {
            database: RawDB { ptr: database },
            options,
        }
    }

    /// Open a new LevelDB instance
    ///
    /// If the LevelDB instance is missing, the behaviour depends on `options.create_if_missing`.
    /// The LevelDB instance will be created using the settings given in `options`.
    pub fn open(name: &Path, options: Options) -> Result<Database, Error> {
        let mut error = ptr::null_mut();

        unsafe {
            let c_string = CString::new(name.to_str().unwrap()).unwrap();
            let c_options = c_options(&options);
            let db = leveldb_open(
                c_options as *const leveldb_options_t,
                c_string.as_bytes_with_nul().as_ptr() as *const c_char,
                &mut error,
            );
            leveldb_options_destroy(c_options);

            if error.is_null() {
                Ok(Database::new(db, options))
            } else {
                Err(Error::new_from_char(error))
            }
        }
    }
}
