import { Component, Inject, OnInit } from '@angular/core';
import { ToastrService } from "ngx-toastr";
import { HttpClient } from "@angular/common/http";
import { MAT_DIALOG_DATA, MatDialog, MatDialogRef } from "@angular/material/dialog";
import { MatTableDataSource } from "@angular/material/table";
import { Client } from "../../groups/model/model";
import { DeleteModalComponent } from "../../../shared/delete_modal/delete-modal/delete-modal.component";
import { ConfigService } from '@services/config.service';

@Component({
  selector: 'app-show-clients',
  templateUrl: './show-clients.component.html',
  styleUrl: './show-clients.component.css'
})
export class ShowClientsComponent implements OnInit {
  baseUrl: string;
  dataSource = new MatTableDataSource<Client>([]);
  length = 0;
  itemsPerPage: number = 10;
  pageSizeOptions: number[] = [5, 10, 20];
  page = 0;
  loading: boolean = false;
  filters: { [key: string]: string } = {};

  protected status = [
    { value: 'off', name: 'Apagado' },
    { value: 'initializing', name: 'Inicializando' },
    { value: 'og-live', name: 'Og Live' },
    { value: 'linux', name: 'Linux' },
    { value: 'linux-session', name: 'Linux Session' },
    { value: 'windows', name: 'Windows' },
    { value: 'mac', name: 'Mac' },
  ];

  columns = [
    { columnDef: 'id', header: 'ID', cell: (client: Client) => client.id },
    { columnDef: 'status', header: 'Estado', cell: (client: Client) => client.status },
    { columnDef: 'name', header: 'Name', cell: (client: Client) => client.name },
    { columnDef: 'ip', header: 'Ip', cell: (client: Client) => client.ip },
    { columnDef: 'mac', header: 'Mac', cell: (client: Client) => client.mac },
    { columnDef: 'organizationalUnit', header: 'Ruta', cell: (client: Client) => client.organizationalUnit },
    { columnDef: 'ogLive', header: 'OgLive', cell: (client: Client) => client.ogLive?.date },
  ];

  displayedColumns: string[] = ['id', 'status', 'name', 'ip', 'mac', 'organizationalUnit', 'ogLive', 'actions'];

  constructor(
    private toastService: ToastrService,
    private http: HttpClient,
    public dialogRef: MatDialogRef<ShowClientsComponent>,
    public dialog: MatDialog,
    private configService: ConfigService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  ngOnInit(): void {
    if (this.data) {
      this.loadData();
    }
  }

  loadData() {
    this.loading = true;
    this.http.get<any>(`${this.baseUrl}/clients?page=${this.page + 1}&itemsPerPage=${this.itemsPerPage}&subnet.id=${this.data.subnetId}`, { params: this.filters }).subscribe(
      (data) => {
        this.dataSource.data = data['hydra:member'];
        this.length = data['hydra:totalItems'];
        this.loading = false;
      },
      (error) => {
        this.loading = false;
      }
    );
  }

  deleteClient(client: any): void {
    const dialogRef = this.dialog.open(DeleteModalComponent, {
      width: '300px',
      data: { name: client.name }
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.http.delete(`${this.baseUrl}/og-dhcp/server/${this.data.subnetUuid}/delete-host/${client.uuid}`, {}).subscribe({
          next: () => {
            this.toastService.success('Cliente eliminado exitosamente de la red');
            this.loadData()
          },
          error: (error) => {
            this.toastService.error(error.error['hydra:description']);
          }
        });
      }
    })
  }

  onNoClick(): void {
    this.dialogRef.close();
  }

  clearStatusFilter(event: Event) {
    event.stopPropagation();
    delete this.filters['status'];
    this.loadData();
  }

  onPageChange(event: any) {
    this.page = event.pageIndex;
    this.itemsPerPage = event.pageSize;
    this.loadData()
  }
}
