import {Component, OnDestroy, OnInit} from '@angular/core';
import {ApiService, FeatureFlagStateDto} from "../../../services/api.service";
import {FeatureFlagList} from "../../../shared/featureflags";
import {takeUntil} from "rxjs/operators";
import {Subject} from "rxjs";
import {EventService} from "../../../services/event.service";

@Component({
  selector: 'app-featureflags',
  templateUrl: './featureflags.component.html',
  styleUrls: ['./featureflags.component.scss']
})
export class FeatureflagsComponent implements OnInit, OnDestroy {
  destroyed$ = new Subject<void>();
  public features: FeatureFlagStateDto[] = [];
  constructor(private apiService: ApiService, private eventService: EventService) {
  }

  ngOnDestroy(): void {
    this.destroyed$.complete();
  }
  ngOnInit(): void {
    this.eventService.featureFlagChanged.pipe(takeUntil(this.destroyed$)).subscribe(result => this.loadFeatureFlags());
    this.loadFeatureFlags();
  }
  private loadFeatureFlags() {

    FeatureFlagList.FeatureFlags.map((featureFlag) => {
      this.apiService.getFeatureFlagState(featureFlag).pipe(takeUntil(this.destroyed$)).subscribe((result) => {
        if(!this.features.find((x) => x.name === result.name)) {
          this.features.push(result);
          this.features.sort((a, b) => {
            if (a.name < b.name) {
              return -1;
            }
            if (a.name > b.name) {
              return 1;
            }
            return 0;
          });
        } else {
          const index = this.features.findIndex((x) => x.name === result.name);
          this.features[index] = result;
        }
      });
    })
  }

  setFeatureFlag(name: string) {
    const ff = this.features.find((featureFlag) => featureFlag.name === name);
    let newState = false;
    if(ff) {
      newState = !ff.state;
    }
    this.apiService.setFeatureFlagState(name, newState).pipe(takeUntil(this.destroyed$)).subscribe((result) => {
      this.loadFeatureFlags();
    });
  }
}
