import { Directive, Input, OnInit, OnDestroy, TemplateRef, ViewContainerRef } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

import { UserService } from 'src/app/core/services';

@Directive({
    selector: '[appShowAuthed]',
    standalone: true
})
export class ShowAuthedDirective implements OnInit, OnDestroy {
    private _auth: Subscription = new Subscription();

    constructor(
        private templateRef: TemplateRef<any>,
        private userService: UserService,
        private viewContainer: ViewContainerRef
    ) { }

    @Input() set appShowAuthed(condition: boolean) {
        this.condition = condition;
    }

    condition: boolean = false;
    //condition: boolean;

    ngOnInit() {

        const isAuthenticated$: Observable<boolean> = this.userService.isAuthenticated; // .pipe(take(1));
        this._auth = isAuthenticated$.subscribe(
            (isAuthenticated) => {
                if (isAuthenticated && this.condition || !isAuthenticated && !this.condition) {
                    this.viewContainer.createEmbeddedView(this.templateRef);
                } else {
                    this.viewContainer.clear();
                }
            }
        );
    }

    ngOnDestroy() {
        this._auth.unsubscribe();
    }

}
