use super::exec::execute_btrfs_command;
use super::super::error::BtrfsError;
use super::super::types::BtrfsSubvolumeEntry;
use crate::process::CommandResult;

pub fn execute(path: &str) -> Result<CommandResult, BtrfsError> {
    execute_btrfs_command(&["subvolume", "list", "-t", path])
}

pub fn parse(output: &str) -> Vec<BtrfsSubvolumeEntry> {
    output
        .lines()
        .filter_map(|line| {
            let line = line.trim();
            if line.is_empty() || line.starts_with("ID") || line.starts_with("--") {
                return None;
            }

            let mut it = line.split_whitespace();
            let id = it.next()?.parse().ok()?;
            let generation = it.next()?.parse().ok()?;
            let top_level = it.next()?.parse().ok()?;

            let path = it.collect::<Vec<&str>>().join(" ");
            if path.is_empty() {
                return None;
            }

            Some(BtrfsSubvolumeEntry {
                id,
                generation,
                top_level,
                path,
            })
        })
        .collect()
}

pub fn execute_and_parse(path: &str) -> Result<Vec<BtrfsSubvolumeEntry>, BtrfsError> {
    let result = execute(path)?;
    Ok(parse(&result.stdout))
}

