use std::path::Path;

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

pub struct FlutterPlugin;

impl Plugin for FlutterPlugin {
    fn name(&self) -> &str {
        "flutter"
    }

    fn description(&self) -> &str {
        "Flutter/Dart build artifacts and pub cache"
    }

    fn scan_directory(&self, dir: &Path) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        let pubspec = dir.join("pubspec.yaml");
        if pubspec.exists() {
            let dart_tool = dir.join(".dart_tool");
            if dart_tool.is_dir() {
                let size = utils::dir_size(&dart_tool);
                targets.push(CleanTarget {
                    label: format!("{}", dart_tool.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(dart_tool),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Dart tool cache, regenerated with `flutter pub get`".to_string(),
                });
            }

            let build = dir.join("build");
            if build.is_dir() {
                let size = utils::dir_size(&build);
                targets.push(CleanTarget {
                    label: format!("{}", build.display()),
                    size_bytes: size,
                    action: CleanAction::DeletePath(build),
                    plugin_name: self.name().to_string(),
                    safety: Safety::Recoverable,
                    explanation: "Flutter build output, regenerated with `flutter build`"
                        .to_string(),
                });
            }
        }

        targets
    }

    fn global_targets(&self) -> Vec<CleanTarget> {
        let mut targets = Vec::new();

        let pub_cache = utils::home_dir().join(".pub-cache");
        if pub_cache.is_dir() {
            let size = utils::dir_size(&pub_cache);
            targets.push(CleanTarget {
                label: format!("{}", pub_cache.display()),
                size_bytes: size,
                action: CleanAction::DeletePath(pub_cache),
                plugin_name: self.name().to_string(),
                safety: Safety::Recoverable,
                explanation: "Dart/Flutter package cache, re-downloaded as needed".to_string(),
            });
        }

        targets
    }

    fn markers(&self) -> &'static [&'static str] {
        &["pubspec.yaml"]
    }
}
