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

@Directive({
  selector: '[appIsExpired]',
})
export class IsExpiredDirective implements OnInit, OnDestroy {
  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) {
            this.isVisible = false;
            this.viewContainerRef.clear();
            return;
          }
          const userExpires = user.expireDate;
          if (!userExpires || dayjs().isBefore(userExpires)) {
            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();
  }
}
