import {inject, Injectable} from '@angular/core';
import {ParticleManagerService} from './particle-manager.service';

/**
 * Service responsible for managing animation frames
 */
@Injectable({
  providedIn: 'root'
})
export class FrameManagerService {
  private readonly particleManager = inject(ParticleManagerService);

  /**
   * Adds a new frame
   */
  addFrame(): void {
    const frames = this.particleManager.getFrames();
    const frameId = `frame-${frames.length}`;

    frames.push(frameId);
    this.particleManager.setFrames(frames);

    const particleData = this.particleManager.getParticleData();
    particleData.frames[frameId] = [];
    this.particleManager.setParticleData(particleData);

    this.switchFrame(frameId);
  }

  /**
   * Switches to a different frame
   */
  switchFrame(frameId: string): void {
    this.particleManager.setCurrentFrame(frameId);
    this.particleManager.clearParticleVisuals();
    this.particleManager.renderFrameParticles(frameId);
  }

  /**
   * Removes a frame
   */
  removeFrame(frameId: string): void {
    const frames = this.particleManager.getFrames();
    const index = frames.indexOf(frameId);

    if (index !== -1) {
      frames.splice(index, 1);
      this.particleManager.setFrames(frames);

      const particleData = this.particleManager.getParticleData();
      delete particleData.frames[frameId];
      this.particleManager.setParticleData(particleData);

      // Switch to first frame if we removed the current one
      if (frameId === this.particleManager.getCurrentFrame() && frames.length > 0) {
        this.switchFrame(frames[0]);
      } else if (frames.length === 0) {
        // If no frames left, add one
        this.addFrame();
      }
    }
  }
}
