import { APIClient } from "./ApiClient";

export interface UploadedFile {
  id: number;
  time_create: number;
  mime_type: string;
  sha512: string;
  file_size: number;
  file_name: string;
  user_id: number;
}

export class FileApi {
  /**
   * Upload a new file
   */
  static async UploadFile(file: File): Promise<UploadedFile> {
    const fd = new FormData();
    fd.append("file", file);
    return (
      await APIClient.exec({
        method: "POST",
        uri: "/file",
        formData: fd,
      })
    ).data;
  }

  /**
   * Get a file information
   */
  static async GetFile(id: number): Promise<UploadedFile> {
    return (
      await APIClient.exec({
        method: "GET",
        uri: `/file/${id}`,
      })
    ).data;
  }

  /**
   * Get a file download URL
   */
  static DownloadURL(file: UploadedFile, forceDownload = false): string {
    return (
      APIClient.backendURL() +
      `/file/${file.id}/download${forceDownload ? "?download=true" : ""}`
    );
  }

  /**
   * Download uploaded file
   */
  static async DownloadUploadedFile(file: UploadedFile): Promise<Blob> {
    return (
      await APIClient.exec({
        method: "GET",
        uri: `/file/${file.id}/download`,
      })
    ).data;
  }
}
