import * as FileService from '../../../bindings/sfxkeeb/fileservice';

export type VideoOpenResult = {
  url: string;
  name: string;
};

export async function openVideo(): Promise<VideoOpenResult | null> {
  const result = await FileService.OpenVideo();
  if (!result.url) return null;
  return { url: result.url, name: result.name };
}

export async function openProject(): Promise<string | null> {
  const text = await FileService.OpenProject();
  return text || null;
}

export async function saveProject(content: string, defaultName = 'project.json'): Promise<boolean> {
  await FileService.SaveProject(content, defaultName);
  return true;
}

async function blobToBase64(blob: Blob): Promise<string> {
  const buffer = await blob.arrayBuffer();
  const bytes = new Uint8Array(buffer);
  let binary = '';
  for (let i = 0; i < bytes.length; i++) {
    binary += String.fromCharCode(bytes[i]!);
  }
  return btoa(binary);
}

export async function saveAudio(blob: Blob, defaultName = 'keyboard_track.wav'): Promise<boolean> {
  const dataBase64 = await blobToBase64(blob);
  await FileService.SaveAudio(dataBase64, defaultName);
  return true;
}
