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 {
  IProjectQuotasCreateOptionsModel
} from '@fleio-api/openstack/project/model/project-quotas-create-options.model';
import { IPermissionsModel } from '@fleio-api/base-model/IPermissionsModel';
import { EMPTY, Observable, of, Subscription } from 'rxjs';
import { ProjectsApiService } from '@fleio-api/openstack/project/projects-api.service';
import { NotificationService } from '@shared/ui-api/notification.service';
import { IActionResult } from '@objects-view/interfaces/actions/action-result';
import { ValidatorsHelper } from '@shared/ui-api/helpers/validators-helper';

@Component({
  selector: 'app-project-cluster-quotas-edit-form',
  templateUrl: './project-cluster-quotas-edit-form.component.html',
  styleUrls: ['./project-cluster-quotas-edit-form.component.scss']
})
export class ProjectClusterQuotasEditFormComponent extends DetailsFormBase<IProjectModel> implements OnInit, OnDestroy {
  clusterQuotasForm = this.formBuilder.group({
    hard_limit: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
  });
  createOptions: IProjectQuotasCreateOptionsModel;
  permissions: IPermissionsModel;
  private componentEventSubscription: Subscription;
  selectedRegion: string;
  quotasAvailable = false;
  loadingQuotas = false;
  quotasId = null;

  constructor(
    private formBuilder: UntypedFormBuilder,
    private projectsApiService: ProjectsApiService,
    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_cluster_quotas'];
      if (this.detailsActions[1].noPermissions) {
        this.clusterQuotasForm.disable();
      }
    }
    if (this.primaryAction) {
      // if primary action is not available yet, it means it will be updated when loading quotas ends
      this.updatePrimaryActionBtn();
    }
  }

  loadClusterQuotas() {
    this.loadingQuotas = true;
    this.projectsApiService.getClusterQuotas(
      this.object.id, this.selectedRegion,
    ).subscribe({
      next: quotas => {
        this.quotasAvailable = true;
        if (quotas?.id) {
          this.quotasId = quotas.id;
        } else {
          this.quotasId = null;
        }
        this.clusterQuotasForm.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.loadClusterQuotas();
      this.componentEventSubscription = this.objectController.componentEvent$.subscribe(region => {
        this.selectedRegion = region;
        this.loadClusterQuotas();
      });
    }
  }

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

    const value = this.clusterQuotasForm.value;
    value.region_id = this.selectedRegion;
    if (this.quotasId) {
      value.quotas_id = this.quotasId;
    }

    this.objectController.loading = true;
    this.projectsApiService.setClusterQuotas(this.object.id, value).subscribe({
      next: (response) => {
        this.notificationService.showMessage($localize`Cluster quotas updated.`);
        if (response.quotas_id) {
          this.quotasId = response.quotas_id;
        }
      }, 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;
    }
  }
}
