import { Component, OnDestroy, OnInit } from '@angular/core';
import { FeatureFlagsDataService } from 'src/app/modules/admin/administration/feature-flags/feature-flags.data.service';
import { FeatureFlag } from 'src/app/model/entities/feature-flag';
import { SpinnerService } from 'src/app/service/spinner.service';
import { catchError, takeUntil } from 'rxjs/operators';
import { InputSwitchChangeEvent } from 'primeng/inputswitch';
import { Subject } from 'rxjs';
import { PermissionsEnum } from 'src/app/model/auth/permissionsEnum';
import { AuthService } from 'src/app/service/auth.service';

@Component({
  selector: 'app-feature-flags',
  templateUrl: './feature-flags.page.html',
  styleUrl: './feature-flags.page.scss',
})
export class FeatureFlagsPage implements OnInit, OnDestroy {
  flags: FeatureFlag[] = [];

  protected unsubscribe$ = new Subject<void>();

  constructor(
    private spinner: SpinnerService,
    private data: FeatureFlagsDataService,
    private auth: AuthService
  ) {}

  async ngOnInit() {
    const isAllowed = await this.auth.hasAnyPermissionLazy([
      PermissionsEnum.administrator,
    ]);
    if (!isAllowed) {
      throw new Error('Unauthorized');
    }

    this.data
      .onUpdate()
      .pipe(takeUntil(this.unsubscribe$))
      .subscribe(() => {
        this.load();
      });

    this.spinner.show();
    this.load();
  }

  ngOnDestroy() {
    this.unsubscribe$.next();
    this.unsubscribe$.complete();
  }

  load() {
    this.data
      .load()
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .subscribe(flags => {
        this.flags = flags;
        this.spinner.hide();
      });
  }

  async change(flag: FeatureFlag, event: InputSwitchChangeEvent) {
    const isAllowed = await this.auth.hasAnyPermissionLazy([
      PermissionsEnum.administrator,
    ]);
    if (!isAllowed) {
      throw new Error('Unauthorized');
    }

    flag.value = event.checked;
    this.spinner.show();
    this.data
      .change(flag)
      .pipe(
        catchError(err => {
          this.spinner.hide();
          throw err;
        })
      )
      .subscribe(() => {
        this.spinner.hide();
      });
  }
}
