import { supportsOpfsProjectStorage } from '@learnitive/project-storage';
import { DirectoryHandleProjectStorage } from './project-storage-directory-handle';

const PROJECT_ROOT_DIRECTORY = 'interactive-projects';

export class OpfsProjectStorage extends DirectoryHandleProjectStorage {
  readonly capabilities = {
    directFilesystem: false,
    persistent: true,
    requiresExport: true,
  } as const;

  private projectDirectoryPromise?: Promise<FileSystemDirectoryHandle>;

  constructor(private readonly projectId: string) {
    super();
    if (!projectId.trim()) {
      throw new Error('OPFS project id cannot be empty');
    }
  }

  protected async getRootDirectory(): Promise<FileSystemDirectoryHandle> {
    if (!supportsOpfsProjectStorage()) {
      throw new Error('Origin Private File System is unavailable in this browser');
    }
    if (!this.projectDirectoryPromise) {
      this.projectDirectoryPromise = navigator.storage
        .getDirectory()
        .then((root) =>
          root.getDirectoryHandle(PROJECT_ROOT_DIRECTORY, { create: true }),
        )
        .then((projects) =>
          projects.getDirectoryHandle(this.projectId, { create: true }),
        );
    }
    return this.projectDirectoryPromise;
  }
}
