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 { Router } from '@angular/router';
import { ConfigService } from '@shared/config/config.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-database-quotas-edit-form',
  templateUrl: './project-database-quotas-edit-form.component.html',
  styleUrls: ['./project-database-quotas-edit-form.component.scss']
})
export class ProjectDatabaseQuotasEditFormComponent extends DetailsFormBase<IProjectModel> implements OnInit, OnDestroy {
  databaseQuotasForm = this.formBuilder.group({
    instances: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    ram: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    volumes: [0, [ValidatorsHelper.requiredIntegerValidator, Validators.min(-1)]],
    backups: [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_database_quotas'];
      if (this.detailsActions[1].noPermissions) {
        this.databaseQuotasForm.disable();
      }
    }
    if (this.primaryAction) {
      // if primary action is not available yet, it means it will be updated when loading quotas ends
      this.updatePrimaryActionBtn();
    }
  }

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

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

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

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