use clap::Parser;
use log::LevelFilter;
use rs_transfer::{
  endpoint::GcsEndpoint,
  list::TreeList,
  secret::{GcsCredential, GcsSecret},
};
use std::convert::TryFrom;

#[derive(Parser, Debug)]
struct Args {
  #[clap(short, long)]
  bucket: String,
  #[clap(short, long)]
  credential_file: String,
  #[clap(short, long, default_value = "/")]
  root_path: String,
  #[clap(short, long)]
  prefix: Option<String>,
}

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

  let args = Args::parse();

  let json = std::fs::read_to_string(&args.credential_file).unwrap();
  let credential: GcsCredential = serde_json::from_str(&json).unwrap();
  let secret = GcsSecret {
    bucket: args.bucket,
    credential,
  };

  unsafe {
    std::env::set_var("SERVICE_ACCOUNT_JSON", json);
  }

  let gcs_tree = GcsEndpoint::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 = gcs_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 = gcs_tree.list_tree(&root_path, prefix).await.unwrap();
    for item in items {
      println!(" - {item:?}");
    }
  }
}
