mod hdf5_previewer;

use env_logger;
use glob;
use hdf5_metno::Result;
use hdf5_previewer::cli;
use log::{debug, info};
use std::path::PathBuf;

/// Main function for hdf5-previewer
fn main() -> Result<()> {
    // setup logging
    // std::env::set_var("RUST_LOG", "debug");
    env_logger::init();

    // read args and discard the first (binary name)
    let args: Vec<String> = std::env::args().collect();
    let args = &args[1..];

    // if argument is not provided, display help and quit
    if args.len() == 0 || args.contains(&"--help".to_string()) {
        cli::help();
        if args.contains(&"--help".to_string()) {
            return Ok(());
        }
        return Err("No arguments provided".into());
    }
    info!("Arguments: {:?}", args);

    // get argument
    for arg in args.iter() {
        debug!("Processing argument: {}", arg);
        let file_or_dir = arg;
        let passed_location = PathBuf::from(file_or_dir);
        if !passed_location.exists() {
            let message = format!("File or directory does not exist: {:?}", passed_location);
            return Err(message.into());
        }

        // runs in either mode: files or directory
        if passed_location.is_file() {
            info!("Reading hdf5 file: {:?}", passed_location);
            let file = cli::read_hdf5(&passed_location)?;
            cli::preview(&file)?;
            continue;
        } else if passed_location.is_dir() {
            info!("Reading hdf5 files in directory: {:?}", passed_location);
            let binding = passed_location.join("**/*.h5");
            let glob_pattern = binding.to_str().unwrap();
            debug!("Reading hdf5 files in: {}", glob_pattern);
            let mut hdf5_files = glob::glob(glob_pattern)
                .unwrap()
                .map(|x| x.unwrap())
                .peekable();
            if hdf5_files.peek().is_none() {
                println!("No hdf5 files found in: '{:?}'", passed_location);
                continue;
            }
            for filename in hdf5_files {
                let file = cli::read_hdf5(&filename)?;
                cli::preview(&file)?;
                println!();
            }
        }
    }

    Ok(())
}
