import { Component, Inject, ViewChild } from '@angular/core';
import { FormArray, 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 { IOpenStackRegionNotificationsSettings } from '@fleio-api/core/model/openstack-notifications.model';
import { FormErrorsComponent } from '@shared/error-handling/form-errors/form-errors.component';
import { IYesNoDialogResult } from '@shared/ui-api/interfaces/yes-no-dialog-result';
import { NotificationService } from '@shared/ui-api/notification.service';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-edit-region-notifications-settings-dialog',
  templateUrl: './edit-region-notifications-settings-dialog.component.html',
  styleUrls: ['./edit-region-notifications-settings-dialog.component.scss']
})
export class EditRegionNotificationsSettingsDialogComponent {
  @ViewChild('formErrors') formErrors: FormErrorsComponent;
  notificationsSettingsForm = this.formBuilder.group({
    region: [''],
    urls: this.formBuilder.array([]),
  });
  dialogTitle = null;
  dialogActions: Array<IAction> = [
    new DialogCallbackAction({
      name: $localize`Update notification settings`,
      primary: true,
      callback: () => this.saveNotificationsSettings(),
    }),
  ];
  dialogForm = this.notificationsSettingsForm;
  backendErrors: Record<string, unknown> = {};
  loading = false;
  urlsSettings = this.notificationsSettingsForm.controls.urls as FormArray;

  constructor(
    public dialogRef: MatDialogRef<EditRegionNotificationsSettingsDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: {
      regionSettings: IOpenStackRegionNotificationsSettings,
      regions: string[],
      amqp_durable_queues: boolean,

    },
    private formBuilder: UntypedFormBuilder,
    private notificationService: NotificationService,
  ) {
  }

  saveNotificationsSettings() {
    if (!this.notificationsSettingsForm.valid) {
      return;
    }

    const notificationSettings: IOpenStackRegionNotificationsSettings = this.notificationsSettingsForm.value
    for (const urlSettings of notificationSettings.urls) {
      if (typeof urlSettings.topic === 'string') {
        urlSettings.topic = (urlSettings.topic as string).split(',');
      }
      if (typeof urlSettings.exchange === 'string') {
        urlSettings.exchange = (urlSettings.exchange as string).split(',');
      }
    }

    this.dialogRef.close(notificationSettings);
  }

  deleteUrlSettings(index: number) {
    if (index < this.urlsSettings.controls.length && index >= 0) {
      const regionNotificationsSettings = this.urlsSettings.controls[index].value;
      this.notificationService.confirmDialog({
        title: $localize`Delete url notification settings`,
        message: $localize`Are you sure you want to delete settings for url ${regionNotificationsSettings.url}`,
      }).subscribe((result: IYesNoDialogResult) => {
        if (result?.button === 'yes') {
          this.urlsSettings.removeAt(index);
        }
      });
    }
  }

  addUrlSettings() {
    const urlsSettings = this.formBuilder.group({
      url: ['', [Validators.required, ValidatorsHelper.urlValidator(['rabbit', 'amqp', 'kombu', 'pika', 'zmq', 'kafka'])]],
      topic: ['notifications', [Validators.required]],
      exchange: ['cinder, glance, keystone, neutron, nova, openstack', [Validators.required]],
      pool: ['', [Validators.required]],
      amqp_durable_queues: [this.data.amqp_durable_queues],
    });

    this.urlsSettings.push(urlsSettings);
  }

  initUrlsControls() {
    for (const {} of this.data.regionSettings.urls) {
      this.addUrlSettings();
    }
  }

  ngOnInit(): void {
    this.initUrlsControls()
    this.notificationsSettingsForm.patchValue(this.data.regionSettings);
    this.dialogTitle = $localize`Edit region notification settings`;
  }
}
