import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { generateId } from '@jscrpt/common';
import * as i0 from "@angular/core";
/**
 * Class used for executing javascript code and obtaining types from executed javascript code
 */
export class CodeExecutor {
    //######################### constructor #########################
    constructor(document) {
        this.document = document;
        //######################### protected fields #########################
        /**
         * Loaded data cache for relations id
         */
        this.loadedDataCache = {};
    }
    //######################### public methods #########################
    /**
     * Loads data from dynamicaly executed code
     * @param relationsId - Id of relations for which is data loaded from code
     * @param code - Code used for obtaining data
     */
    async loadData(relationsId, code) {
        if (this.loadedDataCache[relationsId]) {
            return this.loadedDataCache[relationsId];
        }
        const scriptElement = this.document.createElement('script');
        const loadHelper = `loadType${generateId(12)}`;
        let result = null;
        scriptElement.innerText = `
        (function(exports, loadType, require)
        {
            ${code}

            loadType(exports);
        })({}, ${loadHelper}.loadType, ${loadHelper}.require);`;
        window[loadHelper] =
            {
                loadType: (exp) => result = exp.default ?? null,
                require: (requireName) => {
                    console.log(requireName);
                    return null;
                }
            };
        this.document.getElementsByTagName('head')[0].appendChild(scriptElement);
        delete window[loadHelper];
        scriptElement.remove();
        this.loadedDataCache[relationsId] = result;
        return result;
    }
}
CodeExecutor.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: CodeExecutor, deps: [{ token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable });
CodeExecutor.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: CodeExecutor });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.0.4", ngImport: i0, type: CodeExecutor, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: Document, decorators: [{
                    type: Inject,
                    args: [DOCUMENT]
                }] }] });
//# sourceMappingURL=codeExecutor.service.js.map