import {Component, Inject, OnInit} 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 "../../images/data.service";
import { ConfigService } from "@services/config.service";

@Component({
  selector: 'app-manage-repository',
  templateUrl: './manage-repository.component.html',
  styleUrl: './manage-repository.component.css'
})
export class ManageRepositoryComponent implements OnInit {
  baseUrl: string;
  imageForm: FormGroup<any>;
  repositoryId: string | null = null;
  softwareProfiles: any[] = [];

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

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

  load(): void {
    this.dataService.getImage(this.data).subscribe({
      next: (response) => {
        this.imageForm = this.fb.group({
          name: [response.name, Validators.required],
          ip: [response.ip],
          comments: [response.comments],
        });
        this.repositoryId = response['@id'];
      },
      error: (err) => {
        console.error('Error fetching remote calendar:', err);
      }
    });
  }

  save(): void {
    const payload = {
      name: this.imageForm.value.name,
      ip: this.imageForm.value.ip,
      comments: this.imageForm.value.comments,
    };

    if (this.repositoryId) {
      this.http.put(`${this.baseUrl}${this.repositoryId}`, payload).subscribe(
        (response) => {
          this.toastService.success('Repositorio editada correctamente');
          this.dialogRef.close();
        },
        (error) => {
          this.toastService.error(error['error']['hydra:description']);
        }
      );
    } else {
      this.http.post(`${this.baseUrl}/image-repositories`, payload).subscribe(
        (response) => {
          this.toastService.success('Repositorio añadido correctamente');
          this.dialogRef.close();
        },
        (error) => {
          this.toastService.error(error['error']['hydra:description']);
        }
      );
    }
  }

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