import {
  Directive,
  Input,
  OnDestroy,
  OnInit,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';
import { AccountResDto } from '@api/models';
import { AuthService } from '@core/services';
import { intersection, isEmpty } from 'lodash';
import { ReplaySubject } from 'rxjs';
import { takeUntil, tap } from 'rxjs/operators';

@Directive({
  selector: '[appIsNotReadOnly]',
})
export class IsNotReadOnlyDirective implements OnInit, OnDestroy {
  @Input() appIsNotReadOnly: string[] = [];

  private destroyed$: ReplaySubject<boolean> = new ReplaySubject(1);

  isVisible = false;

  constructor(
    private viewContainerRef: ViewContainerRef,
    private templateRef: TemplateRef<any>,
    private authService: AuthService,
  ) {}

  ngOnInit() {
    this.authService.currentUser
      .pipe(
        takeUntil(this.destroyed$),
        tap((user: AccountResDto | null) => {
          if (!user?.privileges) {
            this.isVisible = false;
            this.viewContainerRef.clear();
            return;
          }
          // const action = Object.keys(this.appVisibleLevel);
          // const levels = this.appVisibleLevel[action[0]];
          const userPrivileges = user.privileges
            .filter((res) => !res.flagReadOnly)
            .map((privilege) => privilege.actionCode);

          if (!isEmpty(intersection(this.appIsNotReadOnly, userPrivileges))) {
            if (!this.isVisible) {
              this.isVisible = true;
              this.viewContainerRef.createEmbeddedView(this.templateRef);
            }
          } else {
            this.isVisible = false;
            this.viewContainerRef.clear();
          }
        }),
      )
      .subscribe();
  }

  ngOnDestroy() {
    this.destroyed$.next(true);
    this.destroyed$.complete();
  }
}
