import {
  Directive,
  Input,
  OnDestroy,
  TemplateRef,
  ViewContainerRef,
  inject
} from '@angular/core';
import {
  Subject,
  Subscription,
  combineLatest,
  distinctUntilChanged,
  tap,
} from 'rxjs';
import { AuthService } from './auth.service';

@Directive({
  selector: '[dksRole]',
  standalone: true,
})
export class RoleDirective implements OnDestroy {
  private hasView = false;
  private subscription = new Subscription();
  private allowedRoles$ = new Subject<string[]>();

  templateRef = inject(TemplateRef);
  viewContainer = inject(ViewContainerRef);
  authService = inject(AuthService);

  @Input() set dksRole(roles: string[]) {
    this.allowedRoles$.next(roles);
  }

  constructor() {
    this.subscription.add(
      combineLatest([
        this.allowedRoles$.pipe(
          distinctUntilChanged((prev, current) =>
            prev.some((item, index) => item !== current[index])
          )
        ),
        this.authService.roles$,
      ])
        .pipe(
          tap(([allowedRoles, userRoles]) => {
            const hasUserAllowedRole = allowedRoles.some((role) =>
              userRoles?.includes(role)
            );
            if (hasUserAllowedRole && !this.hasView) {
              this.viewContainer.createEmbeddedView(this.templateRef);
              this.hasView = true;
            } else if (!hasUserAllowedRole && this.hasView) {
              this.viewContainer.clear();
              this.hasView = false;
            }
          })
        )
        .subscribe()
    );
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
  }
}
