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

@Component({
  selector: 'app-update-database-accessibility-dialog',
  templateUrl: './update-database-accessibility-dialog.component.html',
  styleUrls: ['./update-database-accessibility-dialog.component.scss']
})
export class UpdateDatabaseAccessibilityDialogComponent implements IBaseDialog, OnInit {
  @ViewChild('formErrors') formErrors;
  updateDatabaseAccessibilityForm = this.formBuilder.group({
    is_public: [false, Validators.required],
    allowed_cidrs: this.formBuilder.array([]),
  });
  dialogTitle = $localize`Update accessibility for ${this.data.database_instance.name}`;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Update accessibility`,
      primary: true,
      callback: () => this.updateAccessibility(),
    }),
  ];
  dialogForm = this.updateDatabaseAccessibilityForm;
  loading = false;
  isPublicInfoIcon: IIcon = {
    name: 'info',
    verticalAlign: 'middle',
    fontSize: '20px',
    marginLeft: '5px',
    marginTop: '9px',
    tooltipDirection: 'right',
    tooltip: $localize`Whether the database service is exposed to the public.`
  };

  constructor(
    public dialogRef: MatDialogRef<UpdateDatabaseAccessibilityDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: { database_instance: IDbaasInstanceModel },
    private dbaasInstancesApiService: DbaasInstancesApiService,
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
  ) {
  }

  private createAddress(address='') {
    return this.formBuilder.group({
      address: [address, Validators.required],
    });
  }

  public addAddress() {
    const addresses = this.updateDatabaseAccessibilityForm.get('allowed_cidrs') as UntypedFormArray;
    addresses.push(this.createAddress());
  }

  public removeAddress(index) {
    const addresses = this.updateDatabaseAccessibilityForm.get('allowed_cidrs') as UntypedFormArray;
    addresses.removeAt(index);
  }

  public updateAccessibility() {
    if (this.updateDatabaseAccessibilityForm.invalid) {
      return;
    }
    this.loading = true;
    const cidrs = [];
    this.updateDatabaseAccessibilityForm.controls.allowed_cidrs.value.forEach(addressControl => {
      cidrs.push(addressControl.address);
    });
    this.dbaasInstancesApiService.updateAccessibility(
      this.data.database_instance.id,
      this.updateDatabaseAccessibilityForm.controls.is_public.value,
      cidrs,
    ).subscribe({
      next: () => {
        this.loading = false;
        this.notificationService.showMessage($localize`Accessibility updated.`);
        this.dialogRef.close(true);
      }, error: (error) => {
        this.formErrors.setBackendErrors(error.error);
        this.loading = false;
      }
    });
  }

  ngOnInit() {
    this.updateDatabaseAccessibilityForm.controls.is_public.setValue(this.data.database_instance.access.is_public);
    if (this.data.database_instance.access.hasOwnProperty('allowed_cidrs')) {
      const addresses = this.updateDatabaseAccessibilityForm.get('allowed_cidrs') as UntypedFormArray;
      this.data.database_instance.access.allowed_cidrs.forEach(address => {
        addresses.push(this.createAddress(address));
      });
    }
  }

}
