use laravel::head::Head;
use crate::current;
use crate::params::{IntoParams, Params};
use crate::registry::Registry;
use crate::url::url_of;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Alternates(Vec<(String, String)>);
impl Alternates {
pub fn get(&self, locale: &str) -> Option<&str> {
self.0
.iter()
.find(|(candidate, _)| candidate == locale)
.map(|(_, url)| url.as_str())
}
pub fn locales(&self) -> impl Iterator<Item = &str> {
self.0.iter().map(|(locale, _)| locale.as_str())
}
pub fn iter(&self) -> impl Iterator<Item = (&str, &str)> {
self.0.iter().map(|(locale, url)| (locale.as_str(), url.as_str()))
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn head(&self) -> Head {
self.0
.iter()
.fold(Head::new(), |head, (locale, url)| head.alternate(locale, url))
}
}
impl IntoIterator for Alternates {
type Item = (String, String);
type IntoIter = std::vec::IntoIter<(String, String)>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
pub fn alternates() -> laravel::Result<Alternates> {
build(None, true)
}
pub fn alternates_with(params: impl IntoParams, absolute: bool) -> laravel::Result<Alternates> {
build(Some(params.into_params()), absolute)
}
pub fn laralang_alternates() -> laravel::Result<Alternates> {
alternates()
}
pub fn alternates_head() -> laravel::Result<Head> {
Ok(alternates()?.head())
}
fn build(params: Option<Params>, absolute: bool) -> laravel::Result<Alternates> {
let (Some(registry), Some(matched)) = (
Registry::try_current(),
current::get().and_then(|current| current.route),
) else {
return Ok(Alternates::default());
};
let Some(base) = matched.base else {
return Ok(Alternates::default());
};
let params = match params {
Some(params) if !params.is_empty() => params,
_ => Params::from_pairs(matched.params),
};
let mut urls = Vec::new();
for locale in ®istry.settings().locales {
if let Some(entry) = registry.get(&format!("{locale}.{base}")) {
urls.push((locale.clone(), url_of(&entry, params.clone(), absolute)?));
}
}
Ok(Alternates(urls))
}