flowcull 0.1.0

Fast photo culling with raw/JPEG pair support
//! Export picked photos and remove rejected ones.

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

use anyhow::{Context, Result};

use crate::catalog::{Label, Photo};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExportKind {
    Both,
    Raw,
    Jpeg,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RemoveMode {
    RecycleBin,
    Delete,
}

/// What to do when a file with the same name already exists in the export folder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OnConflict {
    /// Copy under `name (2).ext`, `name (3).ext`, ...
    Rename,
    Skip,
}

/// Result of an export: files copied, skipped because of a name conflict, or failed.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Exported {
    pub copied: usize,
    pub skipped: usize,
    pub failed: usize,
    /// The first copy error, for the status line.
    pub first_error: Option<String>,
}

/// Copy every picked photo's selected files into `dest`. Existing files are never overwritten;
/// a failed copy is counted and the rest still runs.
pub fn export_picks(
    photos: &[Photo],
    kind: ExportKind,
    on_conflict: OnConflict,
    dest: &Path,
) -> Result<Exported> {
    fs::create_dir_all(dest).with_context(|| format!("creating {}", dest.display()))?;
    let mut result = Exported::default();
    for photo in photos.iter().filter(|p| p.label == Label::Pick) {
        let files = match kind {
            ExportKind::Both => [photo.raw.as_deref(), photo.jpeg.as_deref()],
            ExportKind::Raw => [photo.raw.as_deref(), None],
            ExportKind::Jpeg => [photo.jpeg.as_deref(), None],
        };
        for src in files.into_iter().flatten() {
            let name = src.file_name().context("file without name")?;
            let mut target = dest.join(name);
            if target.exists() {
                match on_conflict {
                    OnConflict::Skip => {
                        result.skipped += 1;
                        continue;
                    }
                    OnConflict::Rename => target = free_name(&target),
                }
            }
            match fs::copy(src, &target) {
                Ok(_) => result.copied += 1,
                Err(e) => {
                    result.failed += 1;
                    result
                        .first_error
                        .get_or_insert_with(|| format!("{}: {e}", src.display()));
                }
            }
        }
    }
    Ok(result)
}

/// First of `name (2).ext`, `name (3).ext`, ... that does not exist yet.
fn free_name(path: &Path) -> PathBuf {
    let stem = path.file_stem().unwrap_or_default().to_string_lossy();
    let ext = path
        .extension()
        .map(|e| format!(".{}", e.to_string_lossy()))
        .unwrap_or_default();
    (2..)
        .map(|n| path.with_file_name(format!("{stem} ({n}){ext}")))
        .find(|p| !p.exists())
        .expect("unbounded search")
}

/// Remove all files of rejected photos. Returns the number of files removed.
pub fn remove_rejects(photos: &[Photo], mode: RemoveMode) -> Result<usize> {
    let files: Vec<PathBuf> = photos
        .iter()
        .filter(|p| p.label == Label::Reject)
        .flat_map(|p| p.files().map(Path::to_path_buf))
        .collect();
    match mode {
        RemoveMode::RecycleBin => trash::delete_all(&files).context("moving to recycle bin")?,
        RemoveMode::Delete => {
            for f in &files {
                fs::remove_file(f).with_context(|| format!("deleting {}", f.display()))?;
            }
        }
    }
    Ok(files.len())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn photo(dir: &Path, stem: &str, jpeg: bool, raw: bool, label: Label) -> Photo {
        let mk = |ext: &str| {
            let p = dir.join(format!("{stem}.{ext}"));
            fs::write(&p, stem).unwrap();
            p
        };
        Photo {
            stem: stem.into(),
            jpeg: jpeg.then(|| mk("jpg")),
            raw: raw.then(|| mk("raf")),
            label,
        }
    }

    #[test]
    fn exports_only_picks_of_requested_kind_and_deletes_rejects() {
        let dir = std::env::temp_dir().join(format!("flowcull-ops-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let photos = vec![
            photo(&dir, "a", true, true, Label::Pick),
            photo(&dir, "b", true, false, Label::Pick),
            photo(&dir, "c", true, true, Label::Reject),
            photo(&dir, "d", false, true, Label::Unlabeled),
        ];

        let out = dir.join("out");
        let export = |kind, on_conflict| export_picks(&photos, kind, on_conflict, &out).unwrap();
        let exported = |copied, skipped| Exported {
            copied,
            skipped,
            ..Default::default()
        };

        assert_eq!(export(ExportKind::Raw, OnConflict::Skip), exported(1, 0));
        assert!(out.join("a.raf").exists() && !out.join("a.jpg").exists());
        // a.raf already exists: skipped, the other two copied.
        assert_eq!(export(ExportKind::Both, OnConflict::Skip), exported(2, 1));
        assert!(out.join("b.jpg").exists());
        // All three exist now: renamed copies, originals untouched.
        fs::write(out.join("a.raf"), "old").unwrap();
        assert_eq!(export(ExportKind::Both, OnConflict::Rename), exported(3, 0));
        assert_eq!(fs::read_to_string(out.join("a.raf")).unwrap(), "old");
        assert_eq!(fs::read_to_string(out.join("a (2).raf")).unwrap(), "a");
        assert_eq!(export(ExportKind::Raw, OnConflict::Rename), exported(1, 0));
        assert!(out.join("a (3).raf").exists());
        // A missing source file is counted, the others still copy.
        fs::remove_file(dir.join("b.jpg")).unwrap();
        let r = export(ExportKind::Jpeg, OnConflict::Rename);
        assert_eq!((r.copied, r.failed), (1, 1));
        assert!(r.first_error.unwrap().contains("b.jpg"));

        assert_eq!(remove_rejects(&photos, RemoveMode::Delete).unwrap(), 2);
        assert!(!dir.join("c.jpg").exists() && !dir.join("c.raf").exists());
        assert!(dir.join("a.jpg").exists() && dir.join("d.raf").exists());

        fs::remove_dir_all(&dir).unwrap();
    }
}