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 { IClientModel } from '@fleio-api/client-user/model/client.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ConfigService } from '@shared/config/config.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IAction } from '@objects-view/interfaces/actions/action';
import { DialogCallbackAction } from '@objects-view/actions/dialog-callback-action';
import { IBaseDialog } from '@shared/common-dialogs/base-dialog';

@Component({
  selector: 'app-instance-move-dialog',
  templateUrl: './instance-move-dialog.component.html',
  styleUrls: ['./instance-move-dialog.component.scss']
})
export class InstanceMoveDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  instanceMoveForm = this.formBuilder.group({
    client: ['', Validators.required],
  });
  dialogTitle = $localize`Move instance ${this.data.instance.name || this.data.instance.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Move instance`,
      primary: true,
      callback: () => this.move(),
    }),
  ];
  dialogForm = this.instanceMoveForm;
  backendErrors = {};
  fieldRequiredTxt = $localize`This field is required!`;

  constructor(
    public dialogRef: MatDialogRef<InstanceMoveDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { instance: IInstanceModel },
    private instancesApiService: InstancesApiService,
    private formBuilder: UntypedFormBuilder,
    private config: ConfigService,
    private notificationService: NotificationService,
  ) {
  }

  public move() {
    const client = this.instanceMoveForm.controls.client.value as IClientModel;
    if (!client) {
      return;
    }
    this.loading = true;
    this.instancesApiService.move(this.data.instance.id, client.id).pipe().subscribe(
      (response) => {
        if (response.operation_id) {
          this.notificationService.showMessageWithLink(
            $localize`Move instance operation started.`,
            `utilities/operations/${response.operation_id}`,
            $localize`See details`
          );
        }
        this.loading = false;
        this.dialogRef.close(true);
      }, error => {
        this.loading = false;
        this.backendErrors = error.error;
        this.formErrors.setBackendErrors(this.backendErrors);
      }
    );
  }

  ngOnInit() {
  }

}
