use getset::Getters;
use libntdsextract2::{CDatabase, EntryId};

use crate::walk::{acl_line::AclLine, attribute_line_set::AttributeLineSet};

#[derive(Getters)]
#[getset(get = "pub")]
pub struct EntryAttributes {
    attributes: Vec<AttributeLineSet>,
    sacls: Vec<AclLine>,
    dacls: Vec<AclLine>,
}

impl EntryAttributes {
    pub fn new<'info, 'db>(database: &CDatabase<'info, 'db>, entry_id: EntryId) -> Self {
        let attributes: Vec<_>;
        let sacls;
        let dacls;

        if let Ok(Some(entry)) = database.entry(entry_id) {
            attributes = entry
                .all_attributes()
                .iter()
                .map(|(i, a)| AttributeLineSet::from(database, i, a))
                .collect();

            match entry.security_descriptor(database.sd_table().as_ref().unwrap()) {
                Ok(sd) => {
                    sacls = sd
                        .as_ref()
                        .and_then(|sd| {
                            sd.as_ref().sacl().as_ref().map(|acl| {
                                acl.ace_list()
                                    .iter()
                                    .enumerate()
                                    .map(|(index, ace)| AclLine::from(database, index, ace))
                                    .collect()
                            })
                        })
                        .unwrap_or_default();
                    dacls = sd
                        .and_then(|sd| {
                            sd.as_ref().dacl().as_ref().map(|acl| {
                                acl.ace_list()
                                    .iter()
                                    .enumerate()
                                    .map(|(index, ace)| AclLine::from(database, index, ace))
                                    .collect()
                            })
                        })
                        .unwrap_or_default();
                }
                Err(why) => {
                    log::error!("unable to access security descriptor of {entry_id:?}: {why}");
                    sacls = vec![];
                    dacls = vec![];
                }
            }
        } else {
            log::error!("found no database entry for id {entry_id:?}");
            attributes = vec![];
            sacls = vec![];
            dacls = vec![];
        };

        Self {
            attributes,
            sacls,
            dacls,
        }
    }

    pub fn explode(self) -> (Vec<AttributeLineSet>, Vec<AclLine>, Vec<AclLine>) {
        (self.attributes, self.dacls, self.sacls)
    }
}
