/**
 * Angular wrapper for Bryntum Demo Header
 */
import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { CSSHelper, DemoCodeEditor, AjaxHelper } from '@bryntum/calendar';
import { BryntumButtonComponent } from './bryntum-button.component';

@Component({
    selector : 'bryntum-demo-header',
    template : `
        <header class="demo-header b-bryntum">
            <a id="title" class="title" href="{{ link }}">
                <h1>
                    <svg viewBox="0 0 354.9 144.52" xmlns="http://www.w3.org/2000/svg">
                        <g><path d="m305.63 144.52c-12.47 0-23.53-4.83-31.58-13.28v11.06h-25.54v-142.3h26.75v48.58c7.84-7.64 18.5-12.07 30.37-12.07 27.15 0 49.28 23.33 49.28 54.1s-22.12 53.9-49.28 53.9zm-3.82-83.47c-14.68 0-26.55 13.27-26.55 29.77s11.87 29.16 26.55 29.16 26.55-12.67 26.55-29.16-11.87-29.77-26.55-29.77z"/><path d="m148.02 0h74.01v29.78h-74.01z"/><path d="m0 56.26h222.03v29.78h-222.03z"/><path d="m74.01 112.52h148.02v29.6h-148.02z"/></g>
                    </svg>
                    {{ title }}
                </h1>
            </a>
            <ng-content></ng-content>
            <div id="tools" class="tools">
                <bryntum-theme-combo *ngIf="themeCombo"></bryntum-theme-combo>
                <bryntum-button
                    text="Download Trial"
                    href="{{ downloadLink }}"
                    rendition="filled"
                    style="margin-inline-end: .5em"
                ></bryntum-button>
                <bryntum-button
                    #code
                    icon="b-icon-code"
                    tooltip="Click to show the code viewer"
                    rendition="text"
                    [hidden]="hiddenEditor"
                    (onClick)="toggleCodeEditor()"
                ></bryntum-button>
                <bryntum-button
                    #download
                    icon="b-icon-download"
                    tooltip="Download this demo zip archive"
                    rendition="text"
                    href='#'
                    [hidden]="true"
                ></bryntum-button>
                <bryntum-fullscreen-button></bryntum-fullscreen-button>
            </div>
        </header>`,
    styles : [
    ]
})
export class BryntumDemoHeaderComponent implements OnInit {

    @ViewChild('code', { static : false }) codeButton!: BryntumButtonComponent;
    @ViewChild('download', { static : false }) downloadButton!: BryntumButtonComponent;

    codeEditor?: DemoCodeEditor;

    title = document.title.split(' - ')[1] || document.title;

    isTest = document.location.search.includes('test');

    demoProduct = document.location.href.match(/\/(\w+)(-trial)?\/[-\w]*examples\//)?.[1].toLowerCase() || 'calendar';

    downloadLink = `https://bryntum.com/download/?product=${this.demoProduct}`;

    link = '';

    appFolder = '../../';

    @Input() themeCombo = true;

    hiddenEditor = !Boolean(DemoCodeEditor.monacoCodePath);

    tooltip = {
        html  : 'L{codeButton}',
        align : 't100-b100'
    };

    async ngOnInit() {
        // Convert:
        // https://bryntum.com/products/schedulerpro/examples-scheduler/frameworks/angular/basic/dist/basic/
        // https://bryntum.com/products/schedulerpro/examples/frameworks/angular/basic/dist/basic/
        // To:
        // https://bryntum.com/products/schedulerpro/examples/#example-examples-scheduler-frameworks-angular-basic
        // https://bryntum.com/products/schedulerpro/examples/#example-frameworks-angular-basic
        const match = /(.*?\/)(examples.*?\/frameworks\/.*?)\/dist/.exec(document.location.href);
        this.link = match ? `${match[1]}examples/#example-${match[2].replace(/\//gm, '-').replace('examples-frameworks', 'frameworks')}` : '#';

        if (!this.hiddenEditor) {
            CSSHelper.insertRule('body { flex-flow : row !important }');
            CSSHelper.insertRule('app-root { flex : 1 !important; overflow : hidden !important }');

            const appConfig = (await AjaxHelper.get(`${this.appFolder}app.config.json`, { parseJson : true })).parsedJson;
            if (appConfig.zip || this.isTest) {
                const downloadButton = this.downloadButton.instance;
                downloadButton.hidden = false;
                downloadButton.href = `${this.appFolder}${appConfig.zip}`;
            }
        }

        // Enables special styling when generating screenshots
        const params = new URLSearchParams(window.location.search);
        if (params.has('screenshot')) {
            document.body.classList.add('b-screenshot');
            if ((window as any).bryntum) {
                (window as any).bryntum.noAnimations = true;
            }
        }
    }

    copyShadowRootStyle() {
        const shadowRootStyle = document.querySelector('app-root')?.shadowRoot?.querySelector('style');
        if (shadowRootStyle) {
            document.head.appendChild(shadowRootStyle.cloneNode(true));
        }
    }

    async toggleCodeEditor() {
        if (!this.codeEditor) {
            this.copyShadowRootStyle();
        }

        this.codeEditor = await DemoCodeEditor.toggleCodeEditor(
            this.codeEditor,
            this.codeButton.instance,
            {
                appendTo         : document.body,
                appFolder        : this.appFolder,
                preferredSources : [
                    /\w+\.component\.ts/,
                    /\w+\.config\.ts/
                ]
            }
        );
    }

}
