use crate::utils::{archive::for_each_entry, setup};
use clap::Parser;
use pna::{Archive, EntryBuilder, WriteOptions};
use portable_network_archive::cli;
use std::fs;

/// Precondition: An archive contains entries in alphabetical order.
/// Action: Run `pna experimental sort` with `--by name:desc`.
/// Expectation: Entries are reordered alphabetically by path in descending order.
#[test]
fn sort_by_name_desc() {
    setup();
    fs::create_dir_all("sort_by_name_desc").unwrap();
    let file = fs::File::create("sort_by_name_desc/unsorted.pna").unwrap();
    let mut archive = Archive::write_header(file).unwrap();
    let entry_a = EntryBuilder::new_file("a.txt".into(), WriteOptions::store()).unwrap();
    archive.add_entry(entry_a.build().unwrap()).unwrap();
    let entry_b = EntryBuilder::new_file("b.txt".into(), WriteOptions::store()).unwrap();
    archive.add_entry(entry_b.build().unwrap()).unwrap();
    archive.finalize().unwrap();

    cli::Cli::try_parse_from([
        "pna",
        "--quiet",
        "experimental",
        "sort",
        "-f",
        "sort_by_name_desc/unsorted.pna",
        "--by",
        "name:desc",
    ])
    .unwrap()
    .execute()
    .unwrap();

    let mut names = Vec::new();
    for_each_entry("sort_by_name_desc/unsorted.pna", |e| {
        names.push(e.header().path().as_str().to_string());
    })
    .unwrap();
    assert_eq!(names, ["b.txt", "a.txt"]);
}
