/**
 * PHP Bitmap Font to JSON Converter
 * This script loads PHP bitmap font files and converts them to JavaScript objects
 */

// Use this function to convert PHP font files to JavaScript objects
function convertPhpFontToJs(phpFilePath) {
  // Create a function that loads and parses a PHP font file
  async function loadPhpFont(filePath) {
    try {
      // Fetch the PHP file content
      const response = await fetch(filePath);
      if (!response.ok) {
        throw new Error(`Failed to load font file: ${filePath}`);
      }
      
      const phpCode = await response.text();
      
      // Extract the bitmap array pattern from PHP
      // Looking for patterns like: $numberBitmaps['A'] = [ [...], [...], ... ];
      const bitmapData = {};
      
      // Match character definitions
      const charDefRegex = /\['([^']+)'\]\s*=\s*\[\s*(\[(?:\s*\[[^\]]*\],?)*\s*\])/g;
      let match;
      
      while ((match = charDefRegex.exec(phpCode)) !== null) {
        const char = match[1];
        let arrayText = match[2];
        
        // Clean up array text and convert to JSON format
        arrayText = arrayText.replace(/\s+/g, ' ')  // Normalize whitespace
                             .replace(/\],\s*\[/g, '], [')
                             .replace(/\[\s*\[/g, '[[')
                             .replace(/\]\s*\]/g, ']]');
        
        try {
          // Convert string representation to actual array
          // We need to replace PHP array notation with JS array notation
          arrayText = arrayText.replace(/\s*=>\s*/g, ':');
          
          // Parse the array
          const charArray = JSON.parse(arrayText);
          bitmapData[char] = charArray;
        } catch (parseError) {
          console.error(`Error parsing character '${char}': ${parseError.message}`);
        }
      }
      
      return bitmapData;
    } catch (error) {
      console.error(`Error loading font: ${error.message}`);
      return null;
    }
  }
  
  return loadPhpFont(phpFilePath);
}

/**
 * Font manager that loads PHP fonts on demand and caches them
 */
class FontManager {
  constructor() {
    this.fonts = {};
    this.fontPromises = {};
  }
  
  /**
   * Get font data, loading it if necessary
   * @param {string} fontName - Font name (e.g., 'bitmap_5x7')
   * @returns {Promise<object>} - Font bitmap data
   */
  async getFont(fontName) {
    // Return cached font if available
    if (this.fonts[fontName]) {
      return this.fonts[fontName];
    }
    
    // If already loading, return the existing promise
    if (this.fontPromises[fontName]) {
      return this.fontPromises[fontName];
    }
    
    // Start loading the font - use the correct absolute path
    const fontPath = `/functions/fonts/${fontName}.php`;
    
    console.log(`Loading font from: ${fontPath}`);
    
    this.fontPromises[fontName] = convertPhpFontToJs(fontPath)
      .then(fontData => {
        if (fontData) {
          this.fonts[fontName] = fontData;
          console.log(`Font ${fontName} loaded successfully with ${Object.keys(fontData).length} characters`);
        } else {
          console.error(`Failed to load font ${fontName}`);
        }
        return fontData;
      })
      .catch(error => {
        console.error(`Error loading font ${fontName}:`, error);
        throw error;
      })
      .finally(() => {
        // Clean up the promise when done
        delete this.fontPromises[fontName];
      });
    
    return this.fontPromises[fontName];
  }
}

// Create global font manager instance
window.fontManager = new FontManager();