//! Types related to the DOM text nodes.

use std::sync::Arc;

use crate::ComponentImports;

/// A DOM text node.
#[derive(Clone)]
pub struct DomText {
    inner: Arc<DomTextInner>,
}
struct DomTextInner {
    text: i64,
    component_imports: ComponentImports,
}
impl DomText {
    fn maybe_new(text_handle: i64, imports: &ComponentImports) -> Option<Self> {
        if text_handle == 0 {
            return None;
        }
        Some(DomText {
            inner: Arc::new(DomTextInner {
                text: text_handle,
                component_imports: imports.clone(),
            }),
        })
    }

    pub(crate) fn component_imports(&self) -> &ComponentImports {
        &self.inner.component_imports
    }

    /// Will be deleted once we stop using it.
    pub fn temporary_way_to_get_i64(&self) -> i64 {
        self.to_i64()
    }

    pub(crate) fn to_i64(&self) -> i64 {
        self.inner.text
    }
}
impl Drop for DomTextInner {
    fn drop(&mut self) {
        // TODO: Call a function to free the `self.text`
    }
}

impl ComponentImports {
    /// Create a new text node in the DOM.
    pub fn create_text(&self, text: &str) -> Option<DomText> {
        let text = unsafe {
            afia_component_sys::create_text(self.component_imports_ptr, text.as_ptr(), text.len())
        };

        if text == 0 {
            return None;
        }

        DomText::maybe_new(text, self)
    }
}
