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

@Component({
  selector: 'app-create-software',
  templateUrl: './create-software.component.html',
  styleUrl: './create-software.component.css'
})
export class CreateSoftwareComponent {
  baseUrl: string;
  formGroup: FormGroup<any>;
  private apiUrl: string;
  softwareId: string | null = null;

  constructor(
    private fb: FormBuilder,
    private http: HttpClient,
    public dialogRef: MatDialogRef<CreateSoftwareComponent>,
    private toastService: ToastrService,
    private dataService: DataService,
    private configService: ConfigService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
    this.apiUrl = `${this.baseUrl}/software`;
    this.formGroup = this.fb.group({
      name: ['', Validators.required],
      description: [''],
      type: [''],
    });
  }

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

  load(): void {
    this.dataService.getSoftware(this.data).subscribe({
      next: (response) => {
        console.log(response);
        this.formGroup = this.fb.group({
          name: [response.name, Validators.required],
          description: [response.description],
          type: [response.type],
        });
        this.softwareId = response['@id'];
      },
      error: (err) => {
        console.error('Error fetching software:', err);
      }
    });
  }

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

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

      const payload = {
        name: this.formGroup.value.name,
        description: this.formGroup.value.description,
        type: this.formGroup.value.type,
      };

      if (this.softwareId) {
        this.http.put(`${this.baseUrl}${this.softwareId}`, payload).subscribe(
          (response) => {
            this.toastService.success('Software 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}/software`, payload).subscribe(
          (response) => {
            this.toastService.success('Software añadido correctamente');
            this.dialogRef.close();
          },
          (error) => {
            this.toastService.error(error['error']['hydra:description']);
            console.error('Error al añadir comando', error);
          }
        );
      }
    }
  }
}
