import { Component, Inject, OnInit } 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 { FormBuilder, FormGroup, Validators } from "@angular/forms";
import { ConfigService } from "@services/config.service";

@Component({
  selector: 'app-backup-image',
  templateUrl: './backup-image.component.html',
  styleUrl: './backup-image.component.css'
})
export class BackupImageComponent implements OnInit {
  baseUrl: string;
  loading: boolean = false;
  form!: FormGroup;

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

  ngOnInit(): void {
    this.form = this.fb.group({
      remotePath: ['', Validators.required],
      repoIp: ['', Validators.required]
    });
  }

  save() {
    this.loading = true
    this.http.post<any>(`${this.baseUrl}${this.data.imageImageRepository['@id']}/backup-image`, {
      remotePath: this.form.value.remotePath,
      repoIp: this.form.value.repoIp
    }).subscribe({
      next: (response) => {
        this.toastService.success('Peticion de backup de imagen enviada correctamente');
        this.dialogRef.close();
        this.loading = false;
        this.router.navigate(['/commands-logs']);
      },
      error: error => {
        this.loading = false;
        this.toastService.error('Error al realizar la petición de backup de imagen');
      }
    });
  }

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