import {Injectable} from '@angular/core';
import {DatabasePageComponent} from '../components/editor/database/database-page.component';
import {FileBoxPageComponent} from '../components/nodes/file-box/file-box-page.component';
import {NavigationService} from './navigation.service';
import {EditorService} from './editor.service';
import {ModalController} from '@ionic/angular';
import {debug} from '../utility';

@Injectable({
    providedIn: 'root',
})
export class OpenerService {
    public currentPageId = '';

    constructor(
        protected readonly nav: NavigationService,
        protected readonly editor: EditorService,
        protected readonly ionModalController: ModalController,
    ) { }

    async openTarget(pageId: string, nodeId?: string) {
        if ( !nodeId ) {
            this.currentPageId = pageId;
            return this.nav.requestNavigation(pageId);
        }

        const node = (await this.editor.loadNodes(pageId)).find(rec => rec.UUID === nodeId);
        if ( !node ) {
            this.currentPageId = pageId;
            return this.nav.requestNavigation(pageId);
        }

        if ( node.type === 'database_ref' ) {
            return this.openDatabase(pageId, nodeId);
        }

        if ( node.type === 'file_box' ) {
            return this.openFileBox(pageId, nodeId);
        }

        if ( node.type === 'paragraph' || node.type === 'markdown' ) {
            this.currentPageId = pageId;
            return this.nav.requestNavigation(pageId, node.UUID);
        }

        debug('Unhandled opener node type:', node.type);
    }

    async openDatabase(pageId: string, nodeId: string) {
        const modal = await this.ionModalController.create({
            component: DatabasePageComponent,
            componentProps: {
                nodeId,
                pageId,
            },
            cssClass: 'modal-big',
        });

        const modalState = {
            modal : true,
            desc : 'Open Database'
        };

        history.pushState(modalState, null);

        await modal.present();
    }

    async openFileBox(pageId: string, nodeId: string, boxId?: string) {
        const modal = await this.ionModalController.create({
            component: FileBoxPageComponent,
            componentProps: {
                nodeId,
                pageId,
                boxId,
            },
            cssClass: 'modal-big',
        });

        const modalState = {
            modal : true,
            desc : 'Open File Box'
        };

        history.pushState(modalState, null);

        await modal.present();
    }
}
