use std::path::Path;

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

const CSV_EXTENSIONS: &[&str] = &["csv", "tsv"];

pub struct CsvPlugin;

impl Plugin for CsvPlugin {
    fn name(&self) -> &str {
        "csv"
    }

    fn description(&self) -> &str {
        "Large CSV/TSV 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 CSV_EXTENSIONS.contains(&ext.as_str()) {
                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
    }
}
