//! Debugging utilities.

use crate::{Content, Decoder};
use std::{io::Read, path::PathBuf};

#[derive(Debug)]
pub enum ReadContent {
    Directory,
    Symlink {
        target: PathBuf,
    },
    File {
        executable: bool,
        size: u64,
        offset: u64,
        data: Vec<u8>,
    },
}

/// Pretty print the content of the given [`Decoder`]. The output of
/// this function is unstable.
///
/// Example output:
///
/// ```text
/// ROOT
/// ├── 01-an-empty-file: executable=false, size=0, offset=240, data=''
/// ├── 02-some-dir
/// │   ├── link-to-an-empty-file -> ../01-an-empty-file
/// │   ├── more-depth
/// │   │   ├── deep-empty-file: executable=false, size=0, offset=944, data=''
/// │   ├── small-file: executable=false, size=21, offset=1168, data='This is a test file.\n'
/// ├── 03-executable-file: executable=true, size=0, offset=1456, data=''
/// ```
pub fn pretty_print_nar_content<R: Read>(dec: Decoder<R>) -> String {
    use ReadContent as RC;
    let mut res = vec![];
    for (path, content) in decode_nar(dec) {
        let path = match path {
            None => "ROOT".into(),
            Some(path) => {
                let path = path.display().to_string();
                let components: Vec<&str> = path.split('/').collect();
                match components.last() {
                    Some(basename) => {
                        let depth = components.len();
                        let mut indented = String::new();
                        for _ in 0..depth - 1 {
                            indented.push_str("│   ");
                        }
                        indented.push_str("├── ");
                        indented.push_str(basename);
                        indented
                    }
                    None => "".to_string(),
                }
            }
        };
        res.push(match content {
            RC::Directory => path,
            RC::Symlink { target } => format!("{path} -> {}", target.display()),
            RC::File {
                executable,
                size,
                offset,
                data,
            } => format!(
                "{path}: executable={executable}, size={size}, offset={offset}, data='{}'",
                std::str::from_utf8(&data)
                    .unwrap()
                    .escape_default()
            ),
        });
    }
    res.join("\n")
}

fn decode_nar<R: Read>(dec: Decoder<R>) -> Vec<(Option<PathBuf>, ReadContent)> {
    let mut res = vec![];
    for entry in dec.entries().unwrap() {
        let entry = entry.unwrap();
        let read_content = match entry.content {
            Content::Symlink { target } => ReadContent::Symlink { target },
            Content::Directory => ReadContent::Directory,
            Content::File {
                executable,
                size,
                offset,
                mut data,
            } => {
                let mut read_data: Vec<u8> = vec![];
                data.read_to_end(&mut read_data).unwrap();
                ReadContent::File {
                    executable,
                    size,
                    offset,
                    data: read_data,
                }
            }
        };
        res.push((entry.path, read_content));
    }
    res
}
