﻿import { Component, ViewChild } from '@angular/core';
import { TfabricaSharedService } from './tfabrica.shared.service';
import { Subscription } from 'rxjs/Subscription';
import { Location } from '@angular/common';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { TfabricaUserMenuService } from '../main/tfabrica.usermenu.service';
import { TfabricaUserData } from '../models/tfabrica.userdata.model';
import { TfabricaUserMenu } from '../models/tfabrica.usermenu.model';

@Component({
    selector: 't-sidenav',
    template: require('./tfabrica.sidenav.component.html')
})
export class TfabricaSidenavComponent {

    userData: TfabricaUserData;
    @ViewChild('tleftmenu') tleftmenu;
    loading: boolean;
    menuVoices: TfabricaUserMenu[];
    displayVoices: any[];


    subscription: Subscription;
    subscriptionShared: Subscription;

    constructor(
        private tfabricaSharedService: TfabricaSharedService,
        private tfabricaUserMenuService: TfabricaUserMenuService,
        private router: Router,
        private location: Location
    ) {

        this.userData = tfabricaSharedService.getUser();
        this.loading = false;

        this.menuVoices = [];

        if (this.userData.isLogged) {
            this.createMenu();
        }

        this.subscriptionShared = tfabricaSharedService.userDataLogged$.subscribe(
            userData => {
                this.userData = userData;
                if (this.userData != null) {
                    if (this.userData.isLogged) {
                        this.createMenu();
                    }
                }
            }
        )

        this.subscription = tfabricaSharedService.mainLeftSidenavToggled$.subscribe(
            toogle => {
                this.toggleSidenavMenu();
            }
        )
    }

    toggleSidenavMenu() {
    }

    backToHome() {
        this.tfabricaSharedService.toggleMainLeftSidenav(true);
        this.router.navigate(['/main', { outlets: { 'main': ['home'] } }]);
    }

    goToVoice(voiceName) {
        console.log(voiceName);
        this.tfabricaSharedService.toggleMainLeftSidenav(true);
        this.router.navigate(['/main', { outlets: { 'main': [voiceName] } }]);
    }

    createMenu() {
        if (!this.userData.isLogged) return;

        this.menuVoices = Array<TfabricaUserMenu>();
        this.tfabricaUserMenuService.menu()
            .subscribe(
            userMenus => {
                console.log(userMenus);
                this.menuVoices = userMenus;
                this.loading = false;

                this.designMenu();
            },
            err => {
                // Log errors if any
                console.log(err);
                this.loading = false;
            });
    }

    designMenu() {

        let actThis = this;

        this.displayVoices = Array<TfabricaUserMenu>();

        actThis.attachSubMenu(this.menuVoices);

        console.log(this.displayVoices);
    }

    attachSubMenu(subMenu: Array<TfabricaUserMenu>) {
        let actThis = this;

        subMenu.forEach(function (entry) {
            actThis.displayVoices.push(entry);

            if (entry.isOpen) {
                actThis.attachSubMenu(entry.subMenu);
            }

        });
    }

    selectSingleVoice(singleVoice: TfabricaUserMenu) {
        console.log(singleVoice);
        singleVoice.isOpen = !singleVoice.isOpen;

        let reloadSamePage = false;

        if (singleVoice.subMenu.length == 0) {
            this.tfabricaSharedService.toggleMainLeftSidenav(true);

            var path: string = singleVoice.path;
            console.log(path);

            if (path != null) {

                let newPath = "/main/(main:" + path.substring(1) + ")";
                if (newPath == this.location.path()) {
                    // same url: reload data if change title
                    console.log("Update from Title?");
                    console.log(this.tfabricaSharedService.selectedVoice);

                    try {
                        if (singleVoice.title != this.tfabricaSharedService.selectedVoice.title ||
                            singleVoice.subTitle != this.tfabricaSharedService.selectedVoice.subTitle) {
                            reloadSamePage = true;
                        }
                    } catch (Err) {
                        reloadSamePage = true;
                    }
                }

                if (path.startsWith("/")) {
                    this.tfabricaSharedService.selectedVoice = singleVoice;
                    this.tfabricaSharedService.setSelectedVoice(singleVoice);
                    path = path.substring(1);
                }

                if (path.startsWith("http")) {
                    this.loading = true;
                    window.location.href = path;
                    return;
                }
            }
            
            this.router.navigate(['main', { outlets: { 'main': path } }], { queryParams: { title: singleVoice.title } });
            
        }

        this.designMenu();
    }

    public goToMainApp() {
        console.log(this.tfabricaSharedService.appSettings.mainAppUrl);
        window.location.href = this.tfabricaSharedService.appSettings.mainAppUrl;
    }

    title = this.tfabricaSharedService.appSettings.getAppTitle();

}