use crate::errors::ParseError;
use core::fmt;
use serde_llsd_benthic::{from_str, ser::xml, LLSDValue};
use std::{collections::HashMap, fmt::Display};
#[derive(Debug, Clone, Hash, Eq, PartialEq)]
pub enum Capability {
ViewerAsset,
FetchInventoryDescendents2,
Unknown,
}
impl Capability {
fn from_string(string: &str) -> Self {
match string {
"ViewerAsset" => Self::ViewerAsset,
"FetchInventoryDescendents2" => Self::FetchInventoryDescendents2,
_ => Self::Unknown,
}
}
}
impl Display for Capability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ViewerAsset => write!(f, "ViewerAsset"),
Self::FetchInventoryDescendents2 => write!(f, "FetchInventoryDescendents2"),
Self::Unknown => write!(f, "Unknown"),
}
}
}
#[derive(Debug, Clone)]
pub struct CapabilityRequest {
pub capabilities: String,
}
impl CapabilityRequest {
pub fn new_capability_request(capabilities: Vec<Capability>) -> Result<Self, ParseError> {
let mut capability_vec = Vec::new();
for capability in capabilities {
capability_vec.push(LLSDValue::String(capability.to_string()));
}
let caps = xml::to_string(&LLSDValue::Array(capability_vec), false)?;
Ok(CapabilityRequest { capabilities: caps })
}
pub fn response_from_llsd(xml_bytes: &[u8]) -> Result<HashMap<Capability, String>, ParseError> {
let mut result = HashMap::new();
let xml = String::from_utf8_lossy(xml_bytes).to_string();
let parsed = from_str(&xml)?;
if let Some(parsed_map) = parsed.as_map() {
for (key, val) in parsed_map {
let capability = Capability::from_string(key);
if let LLSDValue::String(value) = val {
result.insert(capability, value.clone());
}
}
}
Ok(result)
}
}