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 { UntypedFormBuilder, Validators } from '@angular/forms';
import { NotificationService } from '@shared/ui-api/notification.service';
import { InstancesApiService } from '@fleio-api/openstack/instance/instances-api.service';
import { PortsApiService } from '@fleio-api/openstack/port/ports-api.service';
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-attach-port-dialog',
  templateUrl: './instance-details-attach-port-dialog.component.html',
  styleUrls: ['./instance-details-attach-port-dialog.component.scss']
})
export class InstanceDetailsAttachPortDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  loading = false;
  backendErrors = {};
  attachPortForm = this.formBuilder.group({
    port: ['', Validators.required]
  });
  dialogTitle = $localize`Attach port to instance ${this.data?.instance?.name || this.data?.instance?.id}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Attach port`,
      primary: true,
      callback: () => this.attachPort(),
    }),
  ];
  dialogForm = this.attachPortForm;
  fieldRequiredTxt = $localize`This field is required!`;
  portOptionsQueryParams: Record<string, string> = {};
  portSelectedPlaceholder = $localize`Port`;
  portUnselectedPlaceholder = $localize`Select port ...`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
    private instancesApi: InstancesApiService,
    public portsApi: PortsApiService,
    public dialogRef: MatDialogRef<InstanceDetailsAttachPortDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      instance: IInstanceModel;
    },
  ) { }

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

  ngOnInit(): void {
    if (this.data && this.data.instance) {
      this.portOptionsQueryParams.filtering = 'project__project_id:' + this.data.instance.project +
        '+network__region:' + this.data.instance.region + '+device_id__exact:';
    }
  }

}
