import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class ImageProcessorService {
  private readonly MODEL_SIZE = 640;

  async processImage(file: File): Promise<Float32Array> {
    const img = await this.loadImage(file);
    const canvas = document.createElement('canvas');
    canvas.width = this.MODEL_SIZE;
    canvas.height = this.MODEL_SIZE;
    
    const ctx = canvas.getContext('2d')!;
    ctx.drawImage(img, 0, 0, this.MODEL_SIZE, this.MODEL_SIZE);
    
    const imageData = ctx.getImageData(0, 0, this.MODEL_SIZE, this.MODEL_SIZE).data;
    return this.preprocess(imageData);
  }

  private loadImage(file: File): Promise<HTMLImageElement> {
    return new Promise((resolve) => {
      const reader = new FileReader();
      reader.onload = (e) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.src = e.target?.result as string;
      };
      reader.readAsDataURL(file);
    });
  }

  // Converts [R,G,B,A, R,G,B,A...] to [R...G...B...] normalized by 255
  private preprocess(data: Uint8ClampedArray): Float32Array {
    const totalPixels = this.MODEL_SIZE * this.MODEL_SIZE;
    const floatData = new Float32Array(3 * totalPixels);
    
    for (let i = 0; i < totalPixels; i++) {
      floatData[i] = data[i * 4] / 255.0;               // Red Channel
      floatData[i + totalPixels] = data[i * 4 + 1] / 255.0;     // Green Channel
      floatData[i + 2 * totalPixels] = data[i * 4 + 2] / 255.0; // Blue Channel
    }
    // Result is in CHW format as required by the ONNX model
    return floatData;
  }
}
