import { Directive, ElementRef, Input, OnInit } from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';

export type BmBooleanBadgeType = 'boolean' | 'success' | 'active' | string;

@Directive({
  selector: '[bm-boolean-badge]',
})
export class BmBooleanBadgeDirective {
  @Input() bmType: BmBooleanBadgeType;
  @Input() reverse?: boolean;

  badgeMap = new Map<boolean, string>([
    [true, 'badge-success'],
    [false, 'badge-danger'],
    [null, 'badge-danger'],
    [undefined, 'badge-danger'],
  ]);

  private readonly directiveDestroyed = new Subject<never>();

  constructor(private elRef: ElementRef<HTMLElement>, private translateService: TranslateService) {}

  @Input('bm-boolean-badge')
  set updateValue(value: boolean) {
    if (this.bmType) {
      this.translateService.onLangChange
        .pipe(takeUntil(this.directiveDestroyed))
        .subscribe(() => (this.elRef.nativeElement.innerText = this.translateService.instant(`global.${this.bmType}.${value}`)));
      this.elRef.nativeElement.innerText = this.translateService.instant(`global.${this.bmType}.${value}`);
    }
    this.elRef.nativeElement.className = `badge ${this.badgeMap.get(this.getValue(value))}`;
  }

  getValue(value: boolean): boolean {
    return this.reverse ? !value : value;
  }
}
