use crate::models::Url;
use ammonia::UrlRelativeEvaluate;
use std::borrow::Cow;

pub struct RelativeUrlEvaluater {
    base_url: Url,
}

impl RelativeUrlEvaluater {
    pub fn new(base_url: Url) -> Self {
        Self { base_url }
    }
}

impl<'a> UrlRelativeEvaluate<'a> for RelativeUrlEvaluater {
    fn evaluate<'url>(&self, relative_url: &'url str) -> Option<std::borrow::Cow<'url, str>> {
        if relative_url.starts_with('#') {
            Some(Cow::Borrowed(relative_url))
        } else {
            self.base_url.join(relative_url).ok().map(|url| Cow::Owned(url.to_string()))
        }
    }
}
