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 { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-export-image',
  templateUrl: './export-image.component.html',
  styleUrl: './export-image.component.css'
})
export class ExportImageComponent implements OnInit {
  baseUrl: string;
  loading: boolean = true;
  repositories: any[] = [];
  selectedRepositories: any[] = [];

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

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

  loadRepositories() {
    const excludedIds = this.data?.image?.imageRepositories?.map((repository: any) => repository.imageRepository?.id) || null;

    let url = `${this.baseUrl}/image-repositories?page=1&itemsPerPage=50`;

    if (excludedIds) {
      url += `&id[neq]=${excludedIds.join(',')}`;
    }

    this.http.get<any>(url)
      .subscribe(
        response => {
          this.repositories = response['hydra:member'];
          this.loading = false;
        },
        error => {
          console.error('Error fetching repositories:', error);
          this.loading = false;
        }
      );
  }

  save() {
    this.loading = true;
    this.http.post<any>(`${this.baseUrl}${this.data.imageImageRepository['@id']}/transfer-image`, {
      repositories: this.selectedRepositories
    }).subscribe({
      next: (response) => {
        this.toastService.success('Petición de exportación de imagen realizada correctamente');
        this.dialogRef.close();
        this.loading = false;
        this.router.navigate(['/commands-logs']);
      },
      error: error => {
        this.loading = false;
        this.toastService.error('Error en la petición de exportación de imagen');
      }
    });
  }

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