use polars_error::{PolarsResult, polars_err};

use super::{DictionaryArray, DictionaryKey};
use crate::array::{FromFfi, PrimitiveArray, ToFfi};
use crate::ffi;

unsafe impl<K: DictionaryKey> ToFfi for DictionaryArray<K> {
    fn buffers(&self) -> Vec<Option<*const u8>> {
        self.keys.buffers()
    }

    fn offset(&self) -> Option<usize> {
        self.keys.offset()
    }

    fn to_ffi_aligned(&self) -> Self {
        Self {
            dtype: self.dtype.clone(),
            keys: self.keys.to_ffi_aligned(),
            values: self.values.clone(),
        }
    }
}

impl<K: DictionaryKey, A: ffi::ArrowArrayRef> FromFfi<A> for DictionaryArray<K> {
    unsafe fn try_from_ffi(array: A) -> PolarsResult<Self> {
        // keys: similar to PrimitiveArray, but the datatype is the inner one
        let validity = unsafe { array.validity() }?;
        let values = unsafe { array.buffer::<K>(1) }?;

        let dtype = array.dtype().clone();

        let keys = PrimitiveArray::<K>::try_new(K::PRIMITIVE.into(), values, validity)?;
        let values = array.dictionary()?.ok_or_else(
            || polars_err!(ComputeError: "Dictionary Array must contain a dictionary in ffi"),
        )?;
        let values = ffi::try_from(values)?;

        // the assumption of this trait
        DictionaryArray::<K>::try_new_unchecked(dtype, keys, values)
    }
}
