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

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

  errorMessage = '';
  clientId: string | null = null;
  partitions: any[] = [];
  images: any[] = [];
  clientName: string = '';
  selectedPartition: any = null;
  name: string = '';
  client: any = null;
  loading: boolean = false;
  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 route: ActivatedRoute,
    private router: Router,
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit() {
    this.clientId = this.route.snapshot.paramMap.get('id');
    this.loadPartitions();
    this.loadImages();
  }

  loadPartitions() {
    const url = `${this.baseUrl}/clients/${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;
          });
        }
      },
      (error) => {
        console.error('Error al cargar los datos del cliente:', error);
      }
    );
  }

  loadImages() {
    const url = `${this.baseUrl}/images?created=false&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;

    const payload = {
      client: `/clients/${this.clientId}`,
      name: this.name,
      partition: this.selectedPartition['@id'],
      source: 'assistant'
    };


    this.http.post(`${this.baseUrl}/images`, payload)
      .subscribe({
        next: (response) => {
          this.toastService.success('Petición de creación de imagen enviada');
          this.loading = false;
          this.router.navigate(['/commands-logs']);
        },
        error: (error) => {
          this.toastService.error(error.error['hydra:description']);
          this.loading = false;
        }
      }
      );
  }
}
