import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { IInstanceModel } from '@fleio-api/openstack/model/instance.model';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { IAction } from '@objects-view/interfaces/actions/action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { FormErrorsComponent } from '@shared/error-handling/form-errors/form-errors.component';

@Component({
  selector: 'app-instance-rename-dialog',
  templateUrl: './instance-rename-dialog.component.html',
  styleUrls: ['./instance-rename-dialog.component.scss']
})
export class InstanceRenameDialogComponent implements IBaseDialog, OnInit {
  instanceRenameForm = this.formBuilder.group({
    name: ['', Validators.required],
  });
  @ViewChild('formErrors') formErrors: FormErrorsComponent;
  dialogTitle = $localize`Rename ${this.data.instance.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Rename`,
      primary: true,
      callback: () => this.rename(),
    }),
  ];
  dialogForm = this.instanceRenameForm;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<InstanceRenameDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { instance: IInstanceModel },
    private instancesApiService: InstancesApiService,
    private formBuilder: UntypedFormBuilder,
  ) {
  }

  public rename() {
    if (this.instanceRenameForm.invalid) {
      return;
    }
    this.loading = true;
    this.instancesApiService.rename(
      this.data.instance.id, this.instanceRenameForm.controls.name.value,
    ).subscribe(() => {
      this.loading = false;
      this.dialogRef.close(true);
    }, (error) => {
      this.loading = false;
      this.formErrors.setBackendErrors(error.error);
    });
  }

  ngOnInit() {
    if (this.data && this.data.instance) {
      this.instanceRenameForm.controls.name.setValue(this.data.instance.name);
    }
  }

}
