import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

import { Overlay, OverlayConfig } from '@angular/cdk/overlay';

import { TemplatePortal } from '@angular/cdk/portal';
import { RESIZE_OBSERVABLE } from './window-resize';
import { ContentsSandbox } from './sandbox';
import {debounceTime} from 'rxjs/operators';

@Directive({
  selector:"[custom-overlay]"
})
export class CustomOverlayDirective { 
    
    @Input() templatePortal: TemplateRef<any> | any;
    
    overlayRef:any;
    clientWidth:any;
    
    constructor(
            public overlay: Overlay,
            private viewContainerRef: ViewContainerRef,
            private contentSandbox: ContentsSandbox) { }
    
    ngOnInit(){
        
        this.clientWidth = document.documentElement.clientWidth;
        
        // changed by Abhishek T on 05-Sep-2019 START
        RESIZE_OBSERVABLE.pipe(debounceTime(200)).subscribe(() => {
            this.clientWidth = document.documentElement.clientWidth;
        });
        // changed by Abhishek T on 05-Sep-2019 END
        
        this.contentSandbox.onAssocOption.subscribe(
          value => {
              console.log('Emitted Value--',value);
              if(value){
                  this.createOverlay();
              } else {
                  console.log('In else--');
                  this.overlayRef.dispose();
              }
          }      
        );

    }
    
    createOverlay() {
        let config = new OverlayConfig();
        let width = '99%';//
        let top = '10px';
        //let height = 'auto';
        let height = '98%';

        config.hasBackdrop = true;
        console.log( 'config & templatePortals ', config, this.templatePortal );

        if ( this.clientWidth < 640 ) {
            width = '98%';
            top = '0';
            height = '100%';
        }

        config.positionStrategy = this.overlay.position()
            .global()
            .centerHorizontally()
            .width( width )
            .top( top )
            .height( height );

        const templatePortal = new TemplatePortal(
            this.templatePortal,
            this.viewContainerRef
        );

        this.overlayRef = this.overlay.create( config );
        this.overlayRef.attach( templatePortal );
    }
    
}