use std::collections::HashMap;
fn strip_slash(path: String) -> String {
let mut out = path;
if out.ends_with("/") {
out.pop();
}
if out.starts_with("/") {
out.remove(0);
}
out
}
pub fn process_path(path: &str, incoming: &str) -> Result<(bool, HashMap<String, String>), String> {
let mut path: String = path.to_string();
let mut incoming = incoming.to_string();
path = strip_slash(path);
incoming = strip_slash(incoming);
let components: Vec<String> = path.split('/').map(|x| x.to_string()).collect();
let mut params: HashMap<String, String> = HashMap::new();
for (index, component) in components.iter().enumerate() {
let mut temp_path = "".to_string();
if component.starts_with(":") {
let key = component[1..].to_string();
let value = incoming.split('/').collect::<Vec<&str>>()[index].to_string();
let cloned_value = value.clone();
params.insert(key, value);
let value = cloned_value;
let updated_path = path.replace(component, &value);
temp_path = updated_path;
incoming = incoming.replace(&value, component);
} else if component.starts_with("**") {
let key = component[2..].to_string();
let value = incoming.split('/').collect::<Vec<&str>>()[index..].join("/");
let cloned_value = value.clone();
params.insert(key, value);
let value = cloned_value;
let updated_path = path.replace(component, &value);
temp_path = updated_path;
incoming = incoming.replace(&value, component);
} else if component == &"*" {
let key = component.to_string();
let value = incoming.split('/').collect::<Vec<&str>>()[index].to_string();
let cloned_value = value.clone();
params.insert(key, value);
let value = cloned_value;
let updated_path = path.replace(component, &value);
temp_path = updated_path;
incoming = incoming.replace(&value, component);
} else if component.starts_with("..") {
return Err("Invalid path".to_string());
} else {
let comps = incoming.split('/').collect::<Vec<&str>>();
if comps.len() <= index || &comps[index] != component {
return Err("Path does not match incoming path".to_string());
}
}
if !temp_path.is_empty() {
path = temp_path;
}
}
Ok((true, params))
}