import { Location } from '@angular/common';
import { ChangeDetectorRef, Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Params, Router } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
import { IframeMsgHandlingService } from '../../../oneit/services/iframe-msg-handling.service';
import { MenuService } from '../../../oneit/services/menu.service';
import { MsgsService } from '../../../oneit/services/msgs.service';
import { UtilsService } from '../../../oneit/services/utils.service';

@Component({
    selector: 'app-admin-iframe-page',
    templateUrl: './admin-iframe-page.component.html',
    styleUrls: ['./admin-iframe-page.component.css']
})
export class AdminIframePageComponent implements OnInit {

    pageURL: string;
    pageLoaded: boolean;
    subscriptions: Array<Subscription> = [];
    showLoader: boolean =   true;

    constructor(
        private changeDetector: ChangeDetectorRef,
        private route: ActivatedRoute,
        private router: Router,
        private location: Location,
        private utilsService: UtilsService,
        public menuService: MenuService,
        public msgsService: MsgsService,
        public iframeMsgHandlingService: IframeMsgHandlingService
    ) { }

    ngOnInit() {
        this.subscriptions.push(this.route.params.subscribe(
            (params: Params) => {
                console.log(params);
                if (params.url) {
                    this.updateLoader(true);
                    this.pageURL = decodeURIComponent(params.url);
                    this.changeDetector.detectChanges();
                    this.msgsService.clearErrorMessages();
                    this.pageLoaded = true;
                }
            }
        ));

        this.subscriptions.push(this.router.events.subscribe(
            (e: any) => {
                // If it is a NavigationEnd event re-initalise the component
                if (e instanceof NavigationEnd) {
                    if (!this.pageLoaded) { //Don't load if params already called
                        this.updateLoader(true);
                        this.pageURL = '';  //Dummy value - else iframe doesnt load when you try to load same url
                        this.changeDetector.detectChanges();
                        setTimeout(() => {
                            this.pageURL = decodeURIComponent(e.url.substring(19)); //Length 13 is based on route path: '/admin/iframe-page/'
                            this.changeDetector.detectChanges();
                            this.msgsService.clearErrorMessages();
                        }, 100);
                    }
                    this.pageLoaded = false;
                }
            }
        ));

        this.subscriptions.push(this.iframeMsgHandlingService.msgReceived.subscribe(
            (message : any) => {
                if(message && message["name"]){
                    if(message["name"] === "loadingCompleted") {
                        this.updateLoader(false);
                    }
                    else if(message["name"] === "loadingStarted") {
                        this.updateLoader(true);
                    }
                }
            }
        ));
    }

    ngOnDestroy() {
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }

    onIframeClick() {
       
    }

    onLoad(iframe) {
        var iframeURL = iframe.contentWindow.location.href;
        if (iframeURL) {
            //this.location.go(this.router.createUrlTree(['../' + encodeURIComponent(iframeURL)], { relativeTo: this.route }).toString());   //So that refresh page works properly
        }
    }

    updateLoader(newValue: boolean){
        this.showLoader =   newValue;
        if(!this.showLoader){
            this.menuService.reloadMenuData(this.subscriptions);  //Reload menu only once loading is completed
            window.scroll(0,0); //scroll to top for all new pages i.e once loading is completed
        }
        this.changeDetector.detectChanges();
    }

}
