import {Component, inject} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {MatInput, MatLabel} from '@angular/material/input';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatCard, MatCardContent, MatCardHeader, MatCardTitle} from '@angular/material/card';
import {MatIconModule} from '@angular/material/icon';
import {MatButtonModule} from '@angular/material/button';
import {ParticlesService} from '@api';
import {ParticleManagerService} from '@pages/particles/services/particle-manager.service';
import {FrameManagerService} from '@pages/particles/services/frame-manager.service';

@Component({
  selector: 'app-particle-manager',
  imports: [
    FormsModule,
    MatFormFieldModule,
    MatInput,
    MatLabel,
    MatCard,
    MatCardContent,
    MatCardHeader,
    MatCardTitle,
    MatIconModule,
    MatButtonModule,
  ],
  templateUrl: './particle-manager.component.html',
  styleUrl: './particle-manager.component.scss'
})
export class ParticleManagerComponent {

  private readonly particlesService = inject(ParticlesService)
  private readonly particleManagerService = inject(ParticleManagerService)
  private readonly frameManagerService = inject(FrameManagerService)

  private selectedParticleName: string = '';

  set selectedParticle(particle: string) {
    this.selectedParticleName = particle;
  }

  get selectedParticle(): string {
    return this.selectedParticleName;
  }

  get createdParticleName(): string {
    return this.particleManagerService.getParticleData().particle_name;
  }

  protected downloadParticle() {
    if (this.selectedParticleName === '') {
      return;
    }
    this.particlesService
      .downloadFile(this.selectedParticleName)
      .subscribe({
          next: data => {
            data.text().then(text => {
              if (text.startsWith('<')) {
                console.error("Failed to download particle: Invalid file format")
                return;
              }
              this.particleManagerService.loadParticleData(text)
              this.frameManagerService.switchFrame(this.particleManagerService.getCurrentFrame())
            })
          },
          error: () => {
            console.error("Failed to download particle: Invalid file name")
          },
        }
      )
  }

  protected uploadParticle() {
    this.particlesService
      .saveFile(this.createdParticleName, new Blob([this.particleManagerService.generateJson()], {type: 'application/json'}))
      .subscribe({
        next: () => {
          console.log("Successfully uploaded particle")
        },
        error: () => {
          console.error("Failed to upload particle")
        }
      })
  }

}
