import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { ApiUsersApiService } from '@fleio-api/openstack/api-user/api-users-api.service';
import { IFloatingIpModel } from '@fleio-api/openstack/floating-ips/model/floating-ip.model';
import { UntypedFormBuilder } from '@angular/forms';
import { ZonesApiService } from '@fleio-api/openstack/zone/zones-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-floating-ip-set-ptr-dialog',
  templateUrl: './floating-ip-set-ptr-dialog.component.html',
  styleUrls: ['./floating-ip-set-ptr-dialog.component.scss']
})
export class FloatingIpSetPtrDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') protected formErrors;
  backendErrors = {};
  setFloatingIpPTRForm = this.formBuilder.group({
    ptrdname: [''],
    description: [''],
    ttl: [''],
  });
  dialogTitle = $localize`Set PTR for ${this.data.floatingIp.floating_ip_address}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save`,
      primary: true,
      callback: () => this.save(),
    }),
  ];
  dialogForm = this.setFloatingIpPTRForm;
  status = null;
  loading = false;

  constructor(
    public dialogRef: MatDialogRef<FloatingIpSetPtrDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      floatingIp: IFloatingIpModel;
    },
    private apiUsersApiService: ApiUsersApiService,
    private formBuilder: UntypedFormBuilder,
    private zonesApiService: ZonesApiService,
  ) {
  }

  save() {
    this.loading = true;
    this.zonesApiService.setFloatingIpPTR(
      this.data.floatingIp.id,
      this.setFloatingIpPTRForm.controls.ptrdname.value,
      this.setFloatingIpPTRForm.controls.description.value,
      this.setFloatingIpPTRForm.controls.ttl.value,
    ).subscribe(result => {
      if (result) {
        this.dialogRef.close($localize`Volume renamed`);
      } else {
        this.dialogRef.close('');
      }
    }, error => {
      if (error?.error) {
        this.backendErrors = error.error;
        this.formErrors.setBackendErrors(error.error);
      }
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit() {
    this.loading = true;
    this.zonesApiService.getFloatingIpPTR(this.data.floatingIp.id).subscribe(response => {
      this.setFloatingIpPTRForm.controls.ptrdname.setValue(response.ptrdname);
      this.setFloatingIpPTRForm.controls.description.setValue(response.description);
      this.setFloatingIpPTRForm.controls.ttl.setValue(response.ttl);
      this.status = response.status;
    }).add(() => {
      this.loading = false;
    });
  }

}
