use std::path::{Path, PathBuf};

use iriencoding::{iridecode, iriencode};

/// https://www.w3.org/TR/rdf11-concepts/#section-IRIs
pub type Iri = iref::IriBuf;

/// Convert a local path into a file IRI
/// 
/// # Examples
/// 
/// ```
/// # use taganak_core::terms::path_to_file_iri;
/// 
/// assert_eq!(
///     path_to_file_iri("/tmp/Fotos von Tieren/Schildkröte.jpg").unwrap().as_str(),
///     "file:///tmp/Fotos%20von%20Tieren/Schildkröte.jpg"
/// );
/// ```
pub fn path_to_file_iri<P: AsRef<Path>>(path: P) -> Option<Iri> {
    let path = path
        .as_ref()
        .to_str()?
        .split('/')
        .map(|c| iriencode(c))
        .collect::<Vec<String>>()
        .join("/");
    Some(Iri::new(format!("file://{}", path)).expect("we iriencoded it"))
}

/// Convert a file IRI to a local path
/// 
/// Does not currently respect a potential hostname in the file IRI.
/// 
/// # Examples
/// 
/// ```
/// # use taganak_core::terms::{Iri, file_iri_to_path};
/// # use std::path::PathBuf;
/// 
/// assert_eq!(
///     file_iri_to_path(Iri::new("file:///tmp/Fotos%20von%20Tieren/Schildkröte.jpg".into()).unwrap()),
///     Some(PathBuf::from("/tmp/Fotos von Tieren/Schildkröte.jpg"))
/// );
/// ```
pub fn file_iri_to_path<I: AsRef<iref::Iri>>(iri: I) -> Option<PathBuf> {
    if iri.as_ref().scheme().as_str() != "file" {
        return None;
    }

    Some(PathBuf::from(iridecode(iri.as_ref().path().as_str())?))
}
