import {EditorPage} from '../editor/editor.page';
import {Component} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Location} from '@angular/common';
import {AlertController, LoadingController, MenuController, ModalController, PopoverController} from '@ionic/angular';
import {EditorService} from '../../service/editor.service';
import {ApiService} from '../../service/api.service';
import {debug} from '../../utility';

@Component({
    selector: 'app-viewer',
    templateUrl: './viewer.page.html',
    styleUrls: ['../editor/editor.page.scss', './viewer.page.scss'],
})
export class ViewerPage extends EditorPage {
    public rootPageId?: string;
    protected cachedRootPageName?: string;
    public menuTree: any[] = [];
    private lookingUpRootPageName = false;

    public get rootPageName(): string {
        if ( !this.cachedRootPageName ) {
            if ( this.pageId === this.rootPageId ) {
                this.cachedRootPageName = this.editorService.mutablePageName;
            } else {
                if ( !this.lookingUpRootPageName ) {
                    this.cachedRootPageName = '';
                    this.lookingUpRootPageName = true;
                    this.lookupRootPageName();
                }
            }
        }

        return this.cachedRootPageName;
    }

    constructor(
        public readonly route: ActivatedRoute,
        public readonly router: Router,
        public readonly loader: LoadingController,
        public readonly popover: PopoverController,
        public readonly alerts: AlertController,
        public readonly modals: ModalController,
        public editorService: EditorService,
        public readonly api: ApiService,
        public readonly menu: MenuController,
        public readonly activatedRoute: ActivatedRoute,
        public readonly location: Location,
    ) {
        super(route, router, loader, popover, alerts, modals, editorService);
        this.editorService = this.editorService.getEditor();
        debug('Viewer page component', this);
    }

    async ionViewDidEnter() {
        this.rootPageId = this.baseId;
        this.menuTree = await this.api.getMenuItems(true, this.rootPageId);
        if ( this.menuTree.length === 1 && this.menuTree[0].virtual ) {
            this.menuTree = this.menuTree[0].children;
        }

        return await super.ionViewDidEnter();
    }

    async openNav() {
        if ( await this.menu.isOpen(`site-${this.rootPageId}`) ) {
            await this.menu.close(`site-${this.rootPageId}`);
        } else {
            await this.menu.enable(true, `site-${this.rootPageId}`);
            await this.menu.open(`site-${this.rootPageId}`);
        }
    }

    async navigate(id: string) {
        await this.editorService.stopEditing();
        await this.editorService.startEditing(id);

        let newLocation: string = window.location.pathname;
        newLocation = newLocation.split(';').filter(x => !x.startsWith('page=')).join(';');
        if ( id !== this.rootPageId ) {
            newLocation += `;page=${id}`;
        }

        this.location.replaceState(newLocation);
    }

    async lookupRootPageName() {
        if ( !this.rootPageId ) {
            this.lookingUpRootPageName = false;
            return;
        }

        const page = await this.editorService.loadPage(this.rootPageId);
        console.log('loaded root page', page);
        this.cachedRootPageName = page.Name;
        this.lookingUpRootPageName = false;
    }
}
