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

@Component({
  selector: 'app-save-script',
  templateUrl: './save-script.component.html',
  styleUrl: './save-script.component.css'
})
export class SaveScriptComponent {
  commandName: string = '';
  baseUrl: string;

  constructor(
    private http: HttpClient,
    public dialogRef: MatDialogRef<SaveScriptComponent>,
    private toastService: ToastrService,
    private configService: ConfigService,
    private dataService: DataService,
    @Inject(MAT_DIALOG_DATA) public data: any
  ) {
    this.baseUrl = this.configService.apiUrl;
  }

  save() {
    const payload = {
      name: this.commandName,
      script: this.data,
      readOnly: false,
      enabled: true,
    };

    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']);
      }
    );
  }

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