import type { LogEvent } from '@ffmpeg/ffmpeg';

export class LogBuffer {
  readonly #maximumEntries: number;
  readonly #maximumCharacters: number;
  #entries: LogEvent[] = [];
  #characters = 0;

  constructor(maximumEntries = 2_000, maximumCharacters = 500_000) {
    this.#maximumEntries = maximumEntries;
    this.#maximumCharacters = maximumCharacters;
  }

  append(event: LogEvent): void {
    const safeEvent = {
      type: event.type,
      message: event.message.replaceAll('\u0000', ''),
    };
    this.#entries.push(safeEvent);
    this.#characters += safeEvent.message.length;

    while (
      this.#entries.length > this.#maximumEntries ||
      this.#characters > this.#maximumCharacters
    ) {
      const removed = this.#entries.shift();
      this.#characters -= removed?.message.length ?? 0;
    }
  }

  clear(): void {
    this.#entries = [];
    this.#characters = 0;
  }

  snapshot(): readonly LogEvent[] {
    return this.#entries.map((event) => ({ ...event }));
  }

  text(): string {
    return this.#entries.map(({ message }) => message).join('\n');
  }
}
