import { Component, ComponentFactoryResolver, ElementRef, OnInit, Type, ViewChild, ViewContainerRef } from "@angular/core";
import { ModalService } from "../../services/modal.service";

@Component({
    selector: 'app-modal',
    templateUrl: './modal.component.html',
    styleUrls: ['./modal.component.scss']
})
export class ModalComponent implements OnInit {
    displayed: boolean = false;
    modalContentClass: Type<unknown> | undefined;
    @ViewChild('modalFrame', { static: true }) modalFrame: ElementRef<HTMLDivElement> | undefined;
    @ViewChild('modalContent', { read: ViewContainerRef }) modalContent: ViewContainerRef | undefined;

    constructor(
        private _componentFactoryResolver: ComponentFactoryResolver,
        private _modalService: ModalService
    ) {}

    ngOnInit(): void {
        this._modalService.modalContent.subscribe(modalContentClass => {
            if (!modalContentClass) {
                this.displayed = false;
                window.setTimeout(() => {
                    if (!this.displayed) {
                        this.modalContent?.detach();
                    }
                }, 1000);
            } else {
                this.displayed = true;
                this.modalContent?.detach();
                const componentFactory = this._componentFactoryResolver.resolveComponentFactory(modalContentClass);
                this.modalContent?.createComponent<unknown>(componentFactory);
            }
        })
    }
}