import { Component, OnDestroy, OnInit } from '@angular/core';
import { DetailsFormBase } from '@objects-view/details-form-base';
import { IProjectModel } from '@fleio-api/openstack/project/model/project.model';
import { UntypedFormBuilder, Validators } from '@angular/forms';
import { ProjectsApiService } from '@fleio-api/openstack/project/projects-api.service';
import { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.service';
import { EMPTY, Observable, of, Subscription } from 'rxjs';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IProjectQuotasCreateOptionsModel } from '@fleio-api/openstack/project/model/project-quotas-create-options.model';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-project-network-quotas-edit-form',
  templateUrl: './project-network-quotas-edit-form.component.html',
  styleUrls: ['./project-network-quotas-edit-form.component.scss']
})
export class ProjectNetworkQuotasEditFormComponent extends DetailsFormBase<IProjectModel> implements OnInit, OnDestroy {
  networkQuotasForm = this.formBuilder.group({
    floatingip: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    network: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    port: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    rbac_policy: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    router: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    security_group: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    security_group_rule: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    subnet: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    subnetpool: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    set_for_all_regions: [false],
  });
  createOptions: IProjectQuotasCreateOptionsModel;
  permissions: IPermissionsModel;
  private componentEventSubscription: Subscription;
  selectedRegion: string;
  quotasAvailable = false;
  loadingQuotas = false;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private projectsApiService: ProjectsApiService,
    private router: Router,
    private config: ConfigService,
    private notificationService: NotificationService,
  ) {
    super();
  }

  initAdditionalObjects() {
    if (!this.createOptions && this.objectController) {
      this.createOptions = this.objectController.additionalObjects.createOptions as IProjectQuotasCreateOptionsModel;
      this.permissions = this.objectController.additionalObjects.permissions as IPermissionsModel;
    }
  }

  protected tabActivated() {
    super.tabActivated();
    this.initAdditionalObjects();
    if (this.objectController) {
      this.objectController.actionCallback = () => this.saveQuotas();
      this.detailsActions[1].noPermissions = !this.permissions['projects.set_network_quotas'];
      if (this.detailsActions[1].noPermissions) {
        this.networkQuotasForm.disable();
      }
    }
    if (this.primaryAction) {
      // if primary action is not available yet, it means it will be updated when loading quotas ends
      this.updatePrimaryActionBtn();
    }
  }

  loadNetworkQuotas() {
    this.loadingQuotas = true;
    this.projectsApiService.getNetworkQuotas(
      this.object.id, this.selectedRegion,
    ).subscribe({
      next: quotas => {
        this.quotasAvailable = true;
        this.networkQuotasForm.patchValue(quotas);
      }, error: () => {
        this.quotasAvailable = false;
      }
    }).add(() => {
      this.loadingQuotas = false;
      this.updatePrimaryActionBtn();
    });
  }

  updatePrimaryActionBtn() {
    if (this.tabActive) {
      this.primaryAction.disabled = !this.quotasAvailable;
    }
  }

  ngOnInit() {
    super.ngOnInit();
    if (this.objectController) {
      this.initAdditionalObjects();

      this.selectedRegion = this.createOptions.selected_region;
      this.loadNetworkQuotas();
      this.componentEventSubscription = this.objectController.componentEvent$.subscribe(region => {
        this.selectedRegion = region;
        this.loadNetworkQuotas();
      });
    }
  }

  saveQuotas(): Observable<IActionResult> {
    this.validate();
    if (this.formGroup.invalid) {
      this.displayControlErrors();
      return EMPTY;
    }

    const value = this.networkQuotasForm.value;
    value.region_id = this.selectedRegion;

    this.objectController.loading = true;
    this.projectsApiService.setNetworkQuotas(this.object.id, value).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Network quotas updated.`);
      }, error: error => {
        if (error.error) {
          this.setErrors(error.error);
        }
      }
    }).add(() => {
      this.objectController.loading = false;
    });

    return of(null);
  }

  ngOnDestroy() {
    if (this.componentEventSubscription) {
      this.componentEventSubscription.unsubscribe();
      this.componentEventSubscription = null;
    }
  }
}

