//! Device tree node utilities
use fdt_rs::{prelude::PropReader, spec::Phandle};

use crate::{
    property::DeviceTreePropertyRead,
    tree::{DeviceTree, TNode, TProp},
};

/// Accessor trait for a device tree node
pub trait DeviceTreeNodeExt<'a> {
    /// Looks up a property with given `name` in the node
    fn property(&self, name: &str) -> Option<TProp<'a>>;
    /// Looks up a child with given `name` in the node
    fn child(&self, name: &str) -> Option<TNode<'a>>;
    /// Looks up a property with given `name` in the nearest parent.
    fn parent_property(&self, name: &str) -> Option<TProp<'a>>;
    /// Returns a property `name`, interpreted as a single string value
    fn prop_string(&self, name: &str) -> Option<&'a str>;
    /// Returns a property `name`, interpreted as a cell of given `size`
    fn prop_cell(&self, name: &str, size: usize) -> Option<u64>;

    /// Returns a property `name`, interpreted as a single cell, cast to [usize]
    fn prop_cell_usize(&self, name: &str) -> Option<usize> {
        self.prop_cell(name, 1).map(|v| v as _)
    }
    /// Returns a property `name`, interpreted as a phandle
    fn prop_phandle(&self, name: &str) -> Option<Phandle> {
        self.prop_cell(name, 1).map(|v| v as _)
    }
    /// Returns `true` if the node contains a property `name`
    fn has_property(&self, name: &str) -> bool {
        self.property(name).is_some()
    }

    /// Returns the `#address-cells` value of the nearest parent
    fn parent_address_cells(&self) -> usize {
        self.parent_property("#address-cells")
            .and_then(|property| property.read_cell(0, 1))
            .unwrap_or(DeviceTree::DEFAULT_ADDRESS_CELLS as u64) as usize
    }
    /// Returns the `#size-cells` value of the nearest parent
    fn parent_size_cells(&self) -> usize {
        self.parent_property("#size-cells")
            .and_then(|property| property.read_cell(0, 1))
            .unwrap_or(DeviceTree::DEFAULT_SIZE_CELLS as u64) as usize
    }
}

impl<'a> DeviceTreeNodeExt<'a> for TNode<'a> {
    fn property(&self, name: &str) -> Option<TProp<'a>> {
        self.props()
            .find(|prop| prop.name().map(|n| n == name).unwrap_or(false))
    }

    fn child(&self, name: &str) -> Option<TNode<'a>> {
        self.children()
            .find(|child| child.name().map(|n| n == name).unwrap_or(false))
    }

    fn parent_property(&self, name: &str) -> Option<TProp<'a>> {
        let mut current = self.parent()?;
        loop {
            if let Some(property) = current.property(name) {
                return Some(property);
            }

            current = current.parent()?;
        }
    }

    fn prop_cell(&self, name: &str, size: usize) -> Option<u64> {
        self.property(name).and_then(|prop| prop.read_cell(0, size))
    }

    fn prop_string(&self, name: &str) -> Option<&'a str> {
        self.property(name).and_then(|prop| prop.str().ok())
    }
}
