use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use super::ResourceFile;
const CATALOG_ROOT: &str = "{ \"info\" : { \"author\" : \"day\", \"version\" : 1 } }\n";
pub fn write_media_xcassets(sources_dir: &Path, images: &[ResourceFile]) -> Result<bool, String> {
if images.is_empty() {
return Ok(false);
}
let catalog = sources_dir.join("Media.xcassets");
let _ = fs::remove_dir_all(&catalog);
fs::create_dir_all(&catalog).map_err(|e| e.to_string())?;
fs::write(catalog.join("Contents.json"), CATALOG_ROOT).map_err(|e| e.to_string())?;
let mut by_name: BTreeMap<&str, Vec<&ResourceFile>> = BTreeMap::new();
for img in images {
by_name.entry(img.name.as_str()).or_default().push(img);
}
for (name, mut variants) in by_name {
variants.sort_by_key(|v| v.scale);
let imageset = catalog.join(format!("{name}.imageset"));
fs::create_dir_all(&imageset).map_err(|e| e.to_string())?;
let mut entries = Vec::new();
for v in &variants {
let ext = v.path.extension().and_then(|e| e.to_str()).unwrap_or("png");
let fname = if v.scale > 1 {
format!("{name}@{}x.{ext}", v.scale)
} else {
format!("{name}.{ext}")
};
fs::copy(&v.path, imageset.join(&fname)).map_err(|e| e.to_string())?;
entries.push(format!(
" {{ \"idiom\" : \"universal\", \"filename\" : \"{fname}\", \"scale\" : \"{}x\" }}",
v.scale
));
}
let contents = format!(
"{{\n \"images\" : [\n{}\n ],\n \"info\" : {{ \"author\" : \"day\", \"version\" : 1 }}\n}}\n",
entries.join(",\n")
);
fs::write(imageset.join("Contents.json"), contents).map_err(|e| e.to_string())?;
}
Ok(true)
}