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-volume-quotas-edit-form',
  templateUrl: './project-volume-quotas-edit-form.component.html',
  styleUrls: ['./project-volume-quotas-edit-form.component.scss']
})
export class ProjectVolumeQuotasEditFormComponent extends DetailsFormBase<IProjectModel> implements OnInit, OnDestroy {
  volumeQuotasForm = this.formBuilder.group({
    volumes: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    snapshots: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    backups: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    groups: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    per_volume_gigabytes: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    gigabytes: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    backup_gigabytes: [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_volume_quotas'];
      if (this.detailsActions[1].noPermissions) {
        this.volumeQuotasForm.disable();
      }
    }
    if (this.primaryAction) {
      // if primary action is not available yet, it means it will be updated when loading quotas ends
      this.updatePrimaryActionBtn();
    }
  }

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

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

  ngOnInit() {
    super.ngOnInit();
    this.initAdditionalObjects();
    if (this.objectController) {
      this.createOptions = this.objectController.additionalObjects.createOptions as IProjectQuotasCreateOptionsModel;
      this.permissions = this.objectController.additionalObjects.permissions as IPermissionsModel;

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

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

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

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