use clap::Parser;
use log::LevelFilter;
use rs_transfer::{endpoint::S3Endpoint, list::TreeList, secret::S3Secret};
use std::convert::TryFrom;

#[derive(Parser, Debug)]
struct Args {
  #[clap(short = 'H', long)]
  hostname: Option<String>,
  #[clap(short, long)]
  access_key_id: String,
  #[clap(short, long)]
  secret_access_key: String,
  #[clap(short = 'R', long)]
  region: Option<String>,
  #[clap(short, long)]
  bucket: String,
  #[clap(short, long, default_value = "/")]
  root_path: String,
  #[clap(long)]
  prefix: Option<String>,
  #[clap(long)]
  role_name: Option<String>,
  #[clap(long)]
  session_name: Option<String>,
}

#[async_std::main]
async fn main() {
  env_logger::builder().filter_level(LevelFilter::Info).init();

  let args = Args::parse();

  let role_name = args.role_name.map(|role| role.into());

  let secret = S3Secret {
    hostname: args.hostname,
    access_key_id: args.access_key_id.into(),
    secret_access_key: args.secret_access_key.into(),
    role_name,
    session_name: args.session_name,
    region: args.region,
    bucket: args.bucket,
  };

  let s3_tree = S3Endpoint::try_from(&secret).unwrap();
  let root_path = &args.root_path;
  let prefix = args.prefix.as_deref();

  println!(
    "\n### List: bucket={}, root_path={root_path}, prefix={prefix:?}",
    secret.bucket
  );
  {
    let items = s3_tree.list(root_path, prefix).await.unwrap();
    for item in items {
      println!(" - {item:?}");
    }
  }

  println!(
    "\n### List tree: bucket={}, root_path={root_path}, prefix={prefix:?}",
    secret.bucket
  );
  {
    let items = s3_tree.list_tree(root_path, prefix).await.unwrap();
    for item in items {
      println!(" - {item:?}");
    }
  }
}
