use crate::{
  StreamData,
  endpoint::{HttpEndpoint, OneDriveEndpoint},
  error::Error,
  reader::{ReaderNotification, StreamReader},
  secret::HttpSecret,
};
use async_std::channel::Sender;
use async_trait::async_trait;
use onedrive_api::ItemLocation;

#[async_trait]
impl StreamReader for OneDriveEndpoint {
  async fn read_stream(
    &self,
    path: &str,
    sender: Sender<StreamData>,
    channel: &dyn ReaderNotification,
  ) -> Result<u64, Error> {
    let item_location =
      ItemLocation::from_path(path).ok_or_else(|| Error::OneDrivePath(path.to_string()))?;
    let drive = self.drive();
    let download_url = drive.get_item_download_url(item_location).await?;

    let http_secret = HttpSecret {
      endpoint: None,
      method: None,
      headers: None,
      body: None,
    };

    let http_reader = HttpEndpoint::from(&http_secret);

    http_reader
      .read_stream(&download_url, sender, channel)
      .await
  }
}
