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-compute-quotas-edit-form',
  templateUrl: './project-compute-quotas-edit-form.component.html',
  styleUrls: ['./project-compute-quotas-edit-form.component.scss']
})
export class ProjectComputeQuotasEditFormComponent extends DetailsFormBase<IProjectModel> implements OnInit, OnDestroy {
  computeQuotasForm = this.formBuilder.group({
    force: [false],
    cores: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    instances: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    key_pairs: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    metadata_items: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    ram: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    server_groups: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    server_group_members: [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_compute_quotas'];
      if (this.detailsActions[1].noPermissions) {
        this.computeQuotasForm.disable();
      }
    }
    if (this.primaryAction) {
      // if primary action is not available yet, it means it will be updated when loading quotas ends
      this.updatePrimaryActionBtn();
    }
  }

  loadComputeQuotas() {
    this.loadingQuotas = true;
    this.projectsApiService.getComputeQuotas(
      this.object.id, this.selectedRegion,
    ).subscribe({
      next: quotas => {
        this.quotasAvailable = true;
        this.computeQuotasForm.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.loadComputeQuotas();
      this.componentEventSubscription = this.objectController.componentEvent$.subscribe(region => {
        this.selectedRegion = region;
        this.loadComputeQuotas();
      });
    }
  }

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

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

    this.objectController.loading = true;
    this.projectsApiService.setComputeQuotas(this.object.id, value).subscribe({
      next: () => {
        this.notificationService.showMessage($localize`Compute 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;
    }
  }
}
