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

@Component({
  selector: 'app-instance-dissociate-ip-dialog',
  templateUrl: './instance-dissociate-ip-dialog.component.html',
  styleUrls: ['./instance-dissociate-ip-dialog.component.scss']
})
export class InstanceDissociateIpDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  backendErrors = {};
  dissociateIpForm = this.formBuilder.group({
    ip: ['', Validators.required],
  });
  dialogTitle = $localize`Dissociate IP from instance ${this.data.instance.name || this.data.instance.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Dissociate ip`,
      primary: true,
      callback: () => this.dissociateIp(),
    }),
  ];
  dialogForm = this.dissociateIpForm;
  ips = [];
  fieldRequiredText = $localize`This field is required`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    private instancesApi: InstancesApiService,
    public dialogRef: MatDialogRef<InstanceDissociateIpDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      instance: IInstanceModel;
      ips: Array<any>;
    },
  ) { }

  public dissociateIp() {
    this.loading = true;
    if (!this.dissociateIpForm.valid) {
      this.loading = false;
      return;
    }
    const value = this.dissociateIpForm.value;
    this.instancesApi.dissociateIp(this.data.instance.id, value.ip).subscribe(response => {
      this.loading = false;
      this.dialogRef.close(true);
    }, error => {
      this.loading = false;
      this.formErrors.setBackendErrors(error.error.detail);
    });
  }

  ngOnInit(): void {
    this.ips = this.data.ips;
    if (this.ips && this.ips.length) {
      this.dissociateIpForm.controls.ip.setValue(this.ips[0].floating_ip_address);
    }
  }

}
