import type { AudioProcessor, ProcessorCategory } from "./AudioProcessor";

export class TrimSilence implements AudioProcessor {
  getName(): string {
    return "Trim Silence";
  }

  getDescription(): string {
    return "Removes leading and trailing silence from audio";
  }

  getCategory(): ProcessorCategory {
    return 'Utility';
  }

  async process(
    leftChannel: Float32Array,
    rightChannel: Float32Array
  ): Promise<[Float32Array, Float32Array]> {
    const threshold = 0.001;

    const startIndex = this.findSoundStart(leftChannel, rightChannel, threshold);
    const endIndex = this.findSoundEnd(leftChannel, rightChannel, threshold);

    if (startIndex >= endIndex) {
      return [new Float32Array(0), new Float32Array(0)];
    }

    const trimmedLength = endIndex - startIndex + 1;
    const newLeft = new Float32Array(trimmedLength);
    const newRight = new Float32Array(trimmedLength);

    for (let i = 0; i < trimmedLength; i++) {
      newLeft[i] = leftChannel[startIndex + i];
      newRight[i] = rightChannel[startIndex + i];
    }

    return [newLeft, newRight];
  }

  private findSoundStart(
    leftChannel: Float32Array,
    rightChannel: Float32Array,
    threshold: number
  ): number {
    for (let i = 0; i < leftChannel.length; i++) {
      if (Math.abs(leftChannel[i]) > threshold || Math.abs(rightChannel[i]) > threshold) {
        return i;
      }
    }
    return leftChannel.length - 1;
  }

  private findSoundEnd(
    leftChannel: Float32Array,
    rightChannel: Float32Array,
    threshold: number
  ): number {
    for (let i = leftChannel.length - 1; i >= 0; i--) {
      if (Math.abs(leftChannel[i]) > threshold || Math.abs(rightChannel[i]) > threshold) {
        return i;
      }
    }
    return 0;
  }
}
