/**
 * Viewer Registry
 * 
 * Manages file viewer plugins and routes files to appropriate viewers.
 */

import { VIEWER_TYPES } from '../lib/constants.js';

class ViewerRegistry {
  constructor() {
    this.viewers = new Map();
  }

  /**
   * Register a viewer
   */
  register(viewer) {
    this.viewers.set(viewer.id, viewer);
    console.log(`[Viewer Registry] Registered viewer: ${viewer.name}`);
  }

  /**
   * Get viewer for a file
   */
  getViewerForFile(metadata) {
    const filename = metadata.filename?.toLowerCase() || '';
    const mimeType = metadata.mimeType?.toLowerCase() || '';
    const ext = '.' + filename.split('.').pop();

    for (const [id, viewer] of this.viewers) {
      // Check extension match
      if (viewer.extensions?.includes(ext)) {
        return viewer;
      }
      // Check mime type match
      if (viewer.mimeTypes?.includes(mimeType)) {
        return viewer;
      }
      // Check custom handler
      if (viewer.canHandle && viewer.canHandle(metadata)) {
        return viewer;
      }
    }

    return null;
  }

  /**
   * Get all registered viewers
   */
  getAll() {
    return Array.from(this.viewers.values());
  }

  /**
   * Check if a file type is supported
   */
  isSupported(metadata) {
    return this.getViewerForFile(metadata) !== null;
  }
}

// Create singleton instance
export const viewerRegistry = new ViewerRegistry();

// Register built-in viewers
viewerRegistry.register({
  id: 'dicom',
  name: 'DICOM Viewer',
  extensions: ['.dcm', '.dicom'],
  mimeTypes: ['application/dicom'],
  viewerUrl: 'src/viewers/dicom/viewer.html',
  canHandle: (metadata) => {
    // Additional DICOM detection logic
    const filename = metadata.filename?.toLowerCase() || '';
    return filename.includes('dicom') || filename.endsWith('.dcm');
  }
});

// PDF viewer (uses browser default for now)
viewerRegistry.register({
  id: 'pdf',
  name: 'PDF Viewer',
  extensions: ['.pdf'],
  mimeTypes: ['application/pdf'],
  viewerUrl: null, // Use blob URL directly (browser handles it)
});

// Image viewer (uses browser default)
viewerRegistry.register({
  id: 'image',
  name: 'Image Viewer',
  extensions: ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'],
  mimeTypes: ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/bmp'],
  viewerUrl: null, // Use blob URL directly
});
