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

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

  errorMessage = '';
  clientId: string | null = null;
  name: string = '';
  client: any = null;
  clientData: any = [];
  loading: boolean = false;
  scripts: any[] = [];
  scriptContent: string = "";
  parameters: string[] = [];
  selectedScript: any = null;
  selectedClients: any[] = [];
  allSelected: boolean = true;
  selection = new SelectionModel(true, []);

  constructor(
    private http: HttpClient,
    private toastService: ToastrService,
    private configService: ConfigService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.route.queryParams.subscribe(params => {
      if (params['clientData']) {
        this.clientData = JSON.parse(params['clientData']);
      }
    });
    this.clientId = this.clientData?.length ? this.clientData[0]['@id'] : null;
    this.clientData.forEach((client: { selected: boolean; status: string}) => {
      if (client.status === 'og-live') {
        client.selected = true;
      }
    });
    this.selectedClients = this.clientData.filter(
      (client: { status: string }) => client.status === 'og-live'
    );
    this.loadScripts()
  }

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

    this.http.get(`${this.baseUrl}/commands?readOnly=false&enabled=true`).subscribe((data: any) => {
      this.scripts = data['hydra:member'];
      this.loading = false;
    }, (error) => {
      this.toastService.error(error.error['hydra:description']);
      this.loading = false;
    });
  }

  toggleClientSelection(client: any) {
    client.selected = !client.selected;
    this.updateSelectedClients();
  }

  updateSelectedClients() {
    this.selectedClients = this.clientData.filter(
      (client: { selected: boolean; status: string }) => client.selected && client.status === "og-live"
    );
  }

  toggleSelectAll() {
    this.allSelected = !this.allSelected;
    this.clientData.forEach((client: { selected: boolean; status: string }) => {
      if (client.status === "og-live") {
        client.selected = this.allSelected;
      }
    });
  }

  getPartitionsTooltip(client: any): string {
    if (!client.partitions || client.partitions.length === 0) {
      return 'No hay particiones disponibles';
    }

    return client.partitions
      .map((p: { partitionNumber: any; size: any; filesystem: any }) => `#${p.partitionNumber} ${p.filesystem} - ${p.size / 1024 }GB`)
      .join('\n');
  }

  onScriptChange() {
    if (this.selectedScript) {
      this.scriptContent = this.selectedScript.script;

      const matches = this.scriptContent.match(/@\d+/g) || [];
      this.parameters = new Array(matches.length).fill("");
    }
  }

  updateScript() {
    let updatedScript = this.selectedScript.script;

    this.parameters.forEach((value, index) => {
      updatedScript = updatedScript.replace(new RegExp(`@${index + 1}`, "g"), value || `@${index + 1}`);
    });

    this.scriptContent = updatedScript;
  }

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

    this.http.post(`${this.baseUrl}/commands/run-script`, {
      clients: this.selectedClients.map((client: any) => client.uuid),
      script: this.scriptContent
    }).subscribe(
      response => {
        this.toastService.success('Script ejecutado correctamente');
        this.dataChange.emit();
      },
      error => {
        this.toastService.error('Error al ejecutar el script');
      }
    );

    this.loading = false;
  }
}
