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 "../../software/data.service";
import { ConfigService } from "@services/config.service";

@Component({
  selector: 'app-create-operative-system',
  templateUrl: './create-operative-system.component.html',
  styleUrl: './create-operative-system.component.css'
})
export class CreateOperativeSystemComponent {
  baseUrl: string;
  formGroup: FormGroup<any>;
  operativeSystemId: string | null = null;

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

  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]
        });
        this.operativeSystemId = 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
      };

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