import { Component, Inject, ViewChild } from '@angular/core';
import { UntypedFormBuilder, Validators } from '@angular/forms';
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 { IPortModel } from '@fleio-api/openstack/model/port.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-details-associate-ip-dialog',
  templateUrl: './instance-details-associate-ip-dialog.component.html',
  styleUrls: ['./instance-details-associate-ip-dialog.component.scss']
})
export class InstanceDetailsAssociateIpDialogComponent implements IBaseDialog {
  @ViewChild('formErrors') formErrors;
  loading = false;
  backendErrors = {};
  associateIpForm = this.formBuilder.group({
    floating_ip: ['', Validators.required],
    fixed_ip: ['', Validators.required]
  });
  dialogTitle = $localize`Assign floating IP for instance ${this.data?.instance?.name || this.data?.instance?.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Associate ip`,
      primary: true,
      callback: () => this.associateIp(),
    }),
  ];
  dialogForm = this.associateIpForm;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private instancesApi: InstancesApiService,
    public dialogRef: MatDialogRef<InstanceDetailsAssociateIpDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      instance: IInstanceModel;
      ports: Array<IPortModel>;
      freeIps: Array<any>;
    },
  ) {
  }

  public associateIp() {
    if (!this.associateIpForm.valid) {
      return;
    }
    const value = this.associateIpForm.value;

    if (!value.fixed_ip?.fixed_ips?.length) {
      this.formErrors.showError($localize`The selected port does not have an IP.`);
      return;
    }

    const fixedIp = value.fixed_ip.fixed_ips[0].ip_address; // get actual fixed ip from port

    this.loading = true;
    this.instancesApi.associateIp(this.data.instance.id, value.floating_ip, fixedIp).subscribe({
      next: () => {
        this.loading = false;
        this.dialogRef.close(true);
      }, error: error => {
        this.formErrors.setBackendErrors(error.error.detail);
      }
    }).add(() => {
      this.loading = false;
    });
  }
}
