use crate::{Error, secret::GcsSecret};
use cloud_storage::Client;
use std::{convert::TryFrom, sync::Arc};

pub struct GcsEndpoint {
  client: Arc<Client>,
  bucket: String,
}

impl TryFrom<&GcsSecret> for GcsEndpoint {
  type Error = Error;

  fn try_from(secret: &GcsSecret) -> Result<Self, Self::Error> {
    Self::new(secret.bucket())
  }
}

impl GcsEndpoint {
  pub fn new(bucket: &str) -> Result<Self, Error> {
    let client = Self::connect()?;
    let client = Arc::new(client);
    let bucket = bucket.to_string();

    Ok(Self { client, bucket })
  }

  fn connect() -> Result<Client, Error> {
    Ok(Client::new())
  }

  pub fn connection(&self) -> Arc<Client> {
    self.client.clone()
  }

  pub fn bucket(&self) -> &str {
    &self.bucket
  }
}
