pub mod authorship;
pub mod ptd;

type Properties = serde_json::Map<String, serde_json::Value>;

pub fn resolve_item_from_mf2(
    mf2_items: Vec<Properties>,
    item_url: &url::Url,
) -> Option<Properties> {
    if mf2_items.is_empty() {
        return None;
    };

    mf2_items
        .iter()
        .cloned()
        .inspect(|x| println!("about to filter for items: {:#?}", x))
        .filter(|item| item.contains_key(&"properties".to_owned()))
        .find(|mf2: &Properties| {
            let no_values: Vec<serde_json::Value> = vec![];
            let expected_url = serde_json::Value::String(item_url.to_string());
            let url_val = mf2["properties"].get("url").cloned().unwrap_or_default();
            let urls = url_val.as_array().unwrap_or(&no_values);
            urls.contains(&expected_url)
        })
        .or_else(|| {
            let no_values = vec![];
            resolve_item_from_mf2(
                mf2_items
                    .iter()
                    .inspect(|x| println!("about to filter for children: {:#?}", x))
                    .filter(|item| item.contains_key(&"children".to_owned()))
                    .map(|item| item["children"].as_array().unwrap_or(&no_values))
                    .flatten()
                    .map(|item| item.as_object().unwrap())
                    .cloned()
                    .collect(),
                item_url,
            )
        })
}
