import { Component, Inject } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { DataService } from "../data.service";
import { ConfigService } from "@services/config.service";

@Component({
  selector: 'app-create-command',
  templateUrl: './create-command.component.html',
  styleUrls: ['./create-command.component.css']
})
export class CreateCommandComponent {
  baseUrl: string;
  createCommandForm: FormGroup<any>;
  commandId: string | null = null;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    public dialogRef: MatDialogRef<CreateCommandComponent>,
    private toastService: ToastrService,
    private configService: ConfigService,
    private dataService: DataService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.createCommandForm = this.fb.group({
      name: ['', Validators.required],
      script: [''],
      readOnly: [false],
      enabled: [true],
      comments: [''],
    });
  }

  ngOnInit(): void {
    if (this.data) {
      this.load()
    }
  }

  load(): void {
    this.dataService.getCommand(this.data).subscribe({
      next: (response) => {
        console.log(response);
        this.createCommandForm = this.fb.group({
          name: [response.name, Validators.required],
          notes: [response.notes],
          script: [response.script],
          readOnly: [response.readOnly],
          enabled: [response.enabled],
        });
        this.commandId = response['@id'];
      },
      error: (err) => {
        console.error('Error fetching remote calendar:', err);
      }
    });
  }

  onCancel(event: Event): void {
    event.preventDefault();
    this.dialogRef.close();
  }

  onSubmit(): void {
    if (this.createCommandForm.valid) {

      const payload = {
        name: this.createCommandForm.value.name,
        script: this.createCommandForm.value.script,
        readOnly: this.createCommandForm.value.readOnly,
        enabled: this.createCommandForm.value.enabled,
        comments: this.createCommandForm.value.comments,
      };

      if (this.commandId) {
        this.http.put(`${this.baseUrl}${this.commandId}`, payload).subscribe(
          (response) => {
            this.toastService.success('Comando editado correctamente');
            this.dialogRef.close();
          },
          (error) => {
            this.toastService.error(error['error']['hydra:description']);
            console.error('Error al editar el comando', error);
          }
        );
      } else {
        this.http.post(`${this.baseUrl}/commands`, payload).subscribe(
          (response) => {
            this.toastService.success('Comando añadido correctamente');
            this.dialogRef.close();
          },
          (error) => {
            this.toastService.error(error['error']['hydra:description']);
            console.error('Error al añadir comando', error);
          }
        );
      }
    }
  }
}
