import { Component, Inject, OnInit, ViewChild } from '@angular/core';
import { ConfigService } from '@shared/config/config.service';
import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material/dialog';
import { UntypedFormBuilder, Validators } 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-edit-ptr-record-dialog',
  templateUrl: './edit-ptr-record-dialog.component.html',
  styleUrls: ['./edit-ptr-record-dialog.component.scss']
})
export class EditPtrRecordDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  backendErrors = {};
  ptrForm = this.formBuilder.group({
    record: ['', Validators.required],
  });
  dialogTitle = null;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Save PTR`,
      primary: true,
      callback: () => this.savePTR(),
    }),
  ];
  dialogForm = this.ptrForm;
  loading = false;
  isCreating = false;
  zoneId = null;
  fieldRequiredTxt = $localize`This field is required!`;

  constructor(
    private formBuilder: UntypedFormBuilder,
    public config: ConfigService,
    private zonesApiService: ZonesApiService,
    public dialogRef: MatDialogRef<EditPtrRecordDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      region: string;
      ip: any;
    },
  ) {
  }

  public savePTR() {
    this.loading = true;
    if (!this.ptrForm.valid) {
      this.loading = false;
      return;
    }
    const value = this.ptrForm.value;
    if (this.zoneId) {
      value.zone_id = this.zoneId;
    }
    value.region_name = this.data.region;
    value.ip = this.data.ip;
    this.zonesApiService.createOrUpdatePTR(value).subscribe({
      next: () => {
        this.dialogRef.close(true);
      }, error: error => {
        this.formErrors.setBackendErrors(error.error.detail);
      }
    }).add(() => {
      this.loading = false;
    });
  }

  ngOnInit(): void {
    this.loading = true;
    this.isCreating = true;

    this.zonesApiService.getPtrFromIp(this.data.ip, this.data.region).subscribe({
      next: response => {
        if (response.zone_id) {
          this.zoneId = response.zone_id;
        }
        if (response.record) {
          this.ptrForm.controls.record.setValue(response.record);
          this.isCreating = false;
        }
      }, error: error => {
        this.formErrors.showError(error.error.detail);
      }
    }).add(() => {
      this.loading = false;
      this.dialogTitle = this.isCreating ? $localize`Create PTR record` : $localize`Update PTR record`;
    });
  }

}
