use std::path::Path;

use crate::plugin::{CleanAction, CleanTarget, DirChild, Plugin, Safety};
use crate::utils;

const IMAGE_EXTENSIONS: &[&str] = &[
    "png", "jpg", "jpeg", "gif", "bmp", "tiff", "tif", "webp", "heic", "heif", "raw", "cr2", "nef",
    "arw", "dng", "orf", "rw2", "psd", "ai", "svg", "ico",
];

pub struct ImagePlugin;

impl Plugin for ImagePlugin {
    fn name(&self) -> &str {
        "image"
    }

    fn description(&self) -> &str {
        "Large image files"
    }

    fn scans_all_directories(&self) -> bool {
        true
    }

    fn scan_with_entries(&self, _dir: &Path, entries: &[DirChild]) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        for child in entries {
            if !child.is_file {
                continue;
            }

            let ext = match Path::new(&child.name).extension().and_then(|e| e.to_str()) {
                Some(e) => e.to_lowercase(),
                None => continue,
            };

            if IMAGE_EXTENSIONS.contains(&ext.as_str())
                && utils::has_mime_prefix(&child.path, "image/")
            {
                let size = child
                    .path
                    .metadata()
                    .map(|m| utils::physical_size(&m))
                    .unwrap_or(0);
                targets.push(CleanTarget {
                    label: format!("{}", child.path.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(child.path.clone()),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Unsafe,
                    explanation: String::new(),
                });
            }
        }

        targets
    }
}
