use apk_tools_sys::{apk_blob_t, apk_dependency_array, apk_string_array};
use std::{ffi::CString, os::raw::c_char};

pub struct ApkDependencyArray(pub *mut apk_dependency_array);

impl Drop for ApkDependencyArray {
    fn drop(&mut self) {
        unsafe { std::ptr::drop_in_place(self.0) };
    }
}

pub struct ApkStringArray(pub *mut apk_string_array);

impl Drop for ApkStringArray {
    fn drop(&mut self) {
        unsafe {
            if let Some(a) = self.0.as_mut() {
                for s in a.as_mut_slice().unwrap() {
                    CString::from_raw(*s);
                }
            }
            std::ptr::drop_in_place(self.0);
        }
    }
}

/**
 * Wrapper around apk_blob_t. apk_blob_t's ptr is sometimes modified (pointer algorithmics), so we save the original pointer here and free it on drop.
 */
pub struct ApkBlobT {
    pub blob: apk_blob_t,
    pub ptr: *mut c_char,
}

impl ApkBlobT {
    pub fn new(string: &str) -> Self {
        let blob = apk_blob_t::new(string);
        Self {
            ptr: blob.ptr,
            blob,
        }
    }
}

impl Drop for ApkBlobT {
    fn drop(&mut self) {
        unsafe {
            CString::from_raw(self.ptr);
        }
    }
}
