import {AfterViewInit, Component, ElementRef, Input, ViewChild, ViewEncapsulation} from '@angular/core';

import {DynamicScriptLoaderService, EndpointConfigService} from 'm2-core';
import {CD_PLUGIN_JS_CTX} from '../../config';


declare const Prism: any;


export type LangCode = 'markup' | 'ts' | 'js' | 'css' | 'json' | string;


@Component({
    selector: 'cd-code',
    template: `<pre class="user-select-on"><code #codeRef [ngClass]="'language-' + langCode"><ng-content></ng-content></code></pre>`,
    styleUrls: [`./cd-code.component.scss`],
    encapsulation: ViewEncapsulation.None
})
export class CdCodeComponent implements AfterViewInit {

    constructor(
        private dynamicScriptLoaderService: DynamicScriptLoaderService,
        private endpointConfigService: EndpointConfigService
    ) {
    }

    @Input() langCode: LangCode = 'markup';

    @ViewChild('codeRef') codeRef: ElementRef<HTMLElement>;


    async ngAfterViewInit(): Promise<void> {
        const paths = [
            '/prism.js',
            '/prism-typescript.min.js'
        ];
        for (const path of paths) {
            await this.dynamicScriptLoaderService.loadScript(this.endpointConfigService.baseUrl + CD_PLUGIN_JS_CTX + path);
        }
        Prism.highlightElement(this.codeRef.nativeElement);
    }

}
