import { Component, EventEmitter, Output } from '@angular/core';
import { MatTableDataSource } from "@angular/material/table";
import { SelectionModel } from "@angular/cdk/collections";
import { HttpClient } from "@angular/common/http";
import { ToastrService } from "ngx-toastr";
import { ActivatedRoute, Router } from "@angular/router";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-deploy-image',
  templateUrl: './deploy-image.component.html',
  styleUrl: './deploy-image.component.css'
})
export class DeployImageComponent {
  baseUrl: string;
  @Output() dataChange = new EventEmitter<any>();

  errorMessage = '';
  clientId: string | null = null;
  partitions: any[] = [];
  images: any[] = [];
  clientName: string = '';
  selectedImage: any = null;
  selectedMethod: string | null = null;
  selectedPartition: any = null;
  mcastIp: string = '';
  mcastPort: Number = 0;
  mcastMode: string = '';
  mcastSpeed: Number = 0;
  mcastMaxClients: Number = 0;
  mcastMaxTime: Number = 0;
  p2pMode: string = '';
  p2pTime: Number = 0;
  name: string = '';
  client: any = null;
  clientData: any = [];
  loading: boolean = false;

  protected p2pModeOptions = [
    { name: 'Leecher', value: 'leecher' },
    { name: 'Peer', value: 'peer' },
    { name: 'Seeder', value: 'seeder' },
  ];
  protected multicastModeOptions = [
    { name: 'Half duplex', value: "half" },
    { name: 'Full duplex', value: "full" },
  ];

  allMethods = [
    'uftp',
    'udpcast',
    'udpcast-direct',
    'unicast',
    'unicast-direct',
    'p2p'
  ];

  dataSource = new MatTableDataSource<any>();
  columns = [
    {
      columnDef: 'diskNumber',
      header: 'Disco',
      cell: (partition: any) => `${partition.diskNumber}`
    },
    {
      columnDef: 'partitionNumber',
      header: 'Particion',
      cell: (partition: any) => `${partition.partitionNumber}`
    },
    {
      columnDef: 'size',
      header: 'Tamaño',
      cell: (partition: any) => `${partition.size} MB`
    },
    {
      columnDef: 'filesystem',
      header: 'Sistema de ficheros',
      cell: (partition: any) => `${partition.filesystem}`
    },
    {
      columnDef: 'operativeSystem',
      header: 'SO',
      cell: (partition: any) => `${partition.operativeSystem?.name}`
    }
  ];

  displayedColumns = ['select', ...this.columns.map(column => column.columnDef)];
  selection = new SelectionModel(true, []);

  constructor(
    private http: HttpClient,
    private toastService: ToastrService,
    private configService: ConfigService,
    private router: Router,
  ) {
    this.baseUrl = this.configService.apiUrl;
    const navigation = this.router.getCurrentNavigation();
    this.clientData = navigation?.extras?.state?.['clientData'];
    this.clientId = this.clientData?.[0]['@id'];
    this.loadImages();
    this.loadPartitions()
  }

  isMethod(method: string): boolean {
    return this.selectedMethod === method;
  }

  loadPartitions() {
    const url = `${this.baseUrl}${this.clientId}`;
    this.http.get(url).subscribe(
      (response: any) => {
        if (response.partitions) {
          this.client = response;
          this.clientName = response.name;
          this.dataSource.data = response.partitions.filter((partition: any) => {
            return partition.partitionNumber !== 0;
          });
          this.p2pMode = response.organizationalUnit?.networkSettings?.p2pMode;
          this.p2pTime = response.organizationalUnit?.networkSettings?.p2pTime;
          this.mcastSpeed = response.organizationalUnit?.networkSettings?.mcastSpeed;
          this.mcastMode = response.organizationalUnit?.networkSettings?.mcastMode;
          this.mcastPort = response.organizationalUnit?.networkSettings?.mcastPort;
          this.mcastIp = response.organizationalUnit?.networkSettings?.mcastIp;
        }
      },
      (error) => {
        console.error('Error al cargar los datos del cliente:', error);
      }
    );
  }

  loadImages() {
    if (!this.clientData || this.clientData.length === 0 || !this.clientData[0]) {
      console.error('Error: clientData es nulo, indefinido o vacío.');
      return;
    }

    const repositoryId =
      this.clientData[0]?.repository?.id ??
      this.clientData[0]?.organizationalUnit?.networkSettings?.repository?.id;

    if (!repositoryId) {
      console.error('Error: No se encontró repositoryId en clientData.');
      return;
    }

    const url = `${this.baseUrl}/image-image-repositories?status=success&repository.id=${repositoryId}&page=1&itemsPerPage=1000`;

    this.http.get(url).subscribe(
      (response: any) => {
        this.images = response?.['hydra:member'] || [];
      },
      (error) => {
        console.error('Error al cargar las imágenes:', error);
      }
    );
  }

  save(): void {
    this.loading = true;

    if (!this.selectedImage) {
      this.toastService.error('Debe seleccionar una imagen');
      this.loading = false;
      return;
    }

    if (!this.selectedMethod) {
      this.toastService.error('Debe seleccionar un método');
      this.loading = false;
      return;
    }

    if (!this.selectedPartition) {
      this.toastService.error('Debe seleccionar una partición');
      this.loading = false;
      return;
    }

    this.toastService.info('Preparando petición de despliegue');

    const payload = {
      clients: this.clientData.map((client: any) => client['@id']),
      method: this.selectedMethod,
      // partition: this.selectedPartition['@id'],
      diskNumber: this.selectedPartition.diskNumber,
      partitionNumber: this.selectedPartition.partitionNumber,
      p2pMode: this.p2pMode,
      p2pTime: this.p2pTime,
      mcastIp: this.mcastIp,
      mcastPort: this.mcastPort,
      mcastMode: this.mcastMode,
      mcastSpeed: this.mcastSpeed,
      maxTime: this.mcastMaxTime,
      maxClients: this.mcastMaxClients,
    };

    this.http.post(`${this.baseUrl}/image-image-repositories/${this.selectedImage.uuid}/deploy-image`, payload)
      .subscribe({
        next: (response) => {
          this.toastService.success('Petición de despliegue enviada correctamente');
          this.loading = false;
          this.router.navigate(['/commands-logs']);
        },
        error: (error) => {
          console.error('Error:', error);
          this.toastService.error(error.error['hydra:description'], 'Se ha detectado un error en el despliegue de imágenes.', {
            "closeButton": true,
            "newestOnTop": false,
            "progressBar": false,
            "positionClass": "toast-bottom-right",
            "timeOut": 0,
            "extendedTimeOut": 0,
            "tapToDismiss": false
          });
          this.loading = false;
        }
      }
      );
  }
}
