import { HttpClient } from '@angular/common/http';
import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ToastrService } from 'ngx-toastr';
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-create-image',
  templateUrl: './create-image.component.html',
  styleUrls: ['./create-image.component.css']
})
export class CreatePXEImageComponent implements OnInit {
  baseUrl: string;
  downloads: any[] = [];
  selectedDownload: any;
  isEditMode: boolean = false;
  loading: boolean = false;
  imageId: string | null = null;

  constructor(
    private toastService: ToastrService,
    private configService: ConfigService,
    private http: HttpClient,
    public dialogRef: MatDialogRef<CreatePXEImageComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit(): void {
    this.fetchDownloads();
    if (this.data) {
      this.isEditMode = true;
      this.selectedDownload = this.data.downloadUrl;
      this.imageId = this.data.uuid;  // Assuming UUID is used for edit
    }
  }

  fetchDownloads(): void {
    this.loading = true;
    this.http.get(`${this.baseUrl}/og-lives/server/get-isos?page=1&itemsPerPage=30`)
      .subscribe({
        next: (response: any) => {
          this.loading = false;
          this.downloads = response.message;
        },
        error: (error) => {
          console.error('Error fetching downloads:', error);
          this.toastService.error('Error fetching iso files');
        }
      });
  }

  onNoClick(): void {
    this.dialogRef.close();
  }

  submitForm(): void {
    const payload = {
      downloadUrl: this.selectedDownload.url
    };

    if (this.isEditMode && this.imageId) {
      this.http.patch(`${this.baseUrl}/og-lives/${this.imageId}`, payload)
        .subscribe({
          next: (response) => {
            this.toastService.success('Image updated successfully');
            this.dialogRef.close(true);
          },
          error: (error) => {
            console.error('Error:', error);
            this.toastService.error(error.error['hydra:description'] || 'Error updating image');
          }
        });
    } else {
      this.http.post(`${this.baseUrl}/og-lives`, payload)
        .subscribe({
          next: (response) => {
            this.toastService.success('Image created successfully');
            this.dialogRef.close(true);
          },
          error: (error) => {
            console.error('Error:', error);
            this.toastService.error(error.error['hydra:description'] || 'Error creating image');
          }
        });
    }
  }
}
