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

@Component({
  selector: 'app-convert-image',
  templateUrl: './convert-image.component.html',
  styleUrl: './convert-image.component.css'
})
export class ConvertImageComponent {
  baseUrl: string;
  loading: boolean = true;
  imageName: string = '';
  filesystem: string = '';

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

  ngOnInit(): void {
    this.loading = true;
  }

  save() {
    console.log(this.data?.repositoryUuid)
    this.http.post<any>(`${this.baseUrl}/image-repositories/${this.data?.repositoryUuid}/convert-image`, {
      name: this.imageName,
      filesystem: this.filesystem
    }).subscribe({
      next: (response) => {
        this.toastService.success('Peticion de conversion de imagen enviada correctamente');
        this.dialogRef.close();
        this.router.navigate(['/commands-logs']);
      },
      error: error => {
        this.toastService.error(error.error['hydra:description']);
      }
    });
  }

  close() {
    this.dialogRef.close();
  }
}
