use crate::config::Config;
use crate::store::Store;
use anyhow::{Context, Result};
use chrono::NaiveDate;
use colored::Colorize;

pub fn run(config: &Config, ref_path: &str, date: NaiveDate, yes: bool) -> Result<()> {
    let store = Store::new(&config.storage_dir);

    // Preview the element before deletion.
    let elements = store.parse_date(date)?;
    let epoch_key = {
        use crate::ref_resolver::RefResolver;
        let resolver = RefResolver::new(&elements);
        resolver
            .to_epoch(ref_path)
            .map(|s| s.to_string())
            .unwrap_or_else(|| ref_path.to_string())
    };
    let el = elements
        .get(&epoch_key)
        .or_else(|| elements.get(ref_path))
        .with_context(|| format!("element '{}' not found for {}", ref_path, date))?;

    let preview = el.body_str().trim().lines().next().unwrap_or("").trim();
    println!("  {} [{}] {} …", "delete:".red().bold(), el.sign(), preview);

    if !yes {
        // Prompt for confirmation.
        print!("  confirm? [y/N] ");
        use std::io::Write;
        std::io::stdout().flush()?;
        let mut answer = String::new();
        std::io::stdin().read_line(&mut answer)?;
        if !answer.trim().eq_ignore_ascii_case("y") {
            println!("  {}", "aborted".dimmed());
            return Ok(());
        }
    }

    let removed = store
        .delete_element(ref_path, date)
        .with_context(|| format!("failed to delete element '{}'", ref_path))?;

    if removed {
        println!("  {} {}", "deleted:".red(), ref_path);
    } else {
        println!(
            "  {} element '{}' was not found in file",
            "warn:".yellow(),
            ref_path
        );
    }

    Ok(())
}
