use std::path::Path;

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

const VIDEO_EXTENSIONS: &[&str] = &[
    "mp4", "mkv", "avi", "mov", "wmv", "flv", "webm", "m4v", "mpg", "mpeg", "3gp", "ts", "vob",
    "ogv", "mts", "m2ts",
];

pub struct VideoPlugin;

impl Plugin for VideoPlugin {
    fn name(&self) -> &str {
        "video"
    }

    fn description(&self) -> &str {
        "Large video 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 VIDEO_EXTENSIONS.contains(&ext.as_str())
                && utils::has_mime_prefix(&child.path, "video/")
            {
                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
    }
}
