import { getParam } from "../engine/engine_utils.js";
const debug = getParam("debugdefines");

// We jump through hoops like this to support 3 cases:
// 1) Vanilla js or angular js where global defines are not guaranteed to be made
// 2) Vite where global defines are made, vite defines are also automatically set to globalThis
// 3) Webpack where global defines are not made BUT declare const variables are replaces with the actual value (via the webpack DefinePlugin)

tryEval(`if(!globalThis["NEEDLE_ENGINE_VERSION"]) globalThis["NEEDLE_ENGINE_VERSION"] = "0.0.0";`);
tryEval(`if(!globalThis["NEEDLE_ENGINE_GENERATOR"]) globalThis["NEEDLE_ENGINE_GENERATOR"] = "unknown";`);
tryEval(`if(!globalThis["NEEDLE_PROJECT_BUILD_TIME"]) globalThis["NEEDLE_PROJECT_BUILD_TIME"] = "unknown";`);
tryEval(`if(!globalThis["NEEDLE_PUBLIC_KEY"]) globalThis["NEEDLE_PUBLIC_KEY"] = "unknown";`);

declare const NEEDLE_ENGINE_VERSION: string
declare const NEEDLE_ENGINE_GENERATOR: string;
declare const NEEDLE_PROJECT_BUILD_TIME: string;
declare const NEEDLE_PUBLIC_KEY: string;

// Make sure to wrap the new global this define in underscores to prevent the bundler from replacing it with the actual value
tryEval(`globalThis["__NEEDLE_ENGINE_VERSION__"] = "` + NEEDLE_ENGINE_VERSION + `";`);
tryEval(`globalThis["__NEEDLE_ENGINE_GENERATOR__"] = "` + NEEDLE_ENGINE_GENERATOR + `";`);
tryEval(`globalThis["__NEEDLE_PROJECT_BUILD_TIME__"] = "` + NEEDLE_PROJECT_BUILD_TIME + `";`);
tryEval(`globalThis["__NEEDLE_PUBLIC_KEY__"] = "` + NEEDLE_PUBLIC_KEY + `";`);

/** The version of the Needle engine */
export const VERSION = NEEDLE_ENGINE_VERSION;
/** The generator used to export the scene / build the web project */
export const GENERATOR = NEEDLE_ENGINE_GENERATOR;
/** The build time of the project */
export const BUILD_TIME = NEEDLE_PROJECT_BUILD_TIME;
if (debug) console.log(`Engine version: ${VERSION} (generator: ${GENERATOR})\nProject built at ${BUILD_TIME}`);

export const PUBLIC_KEY = NEEDLE_PUBLIC_KEY;

export const activeInHierarchyFieldName = "needle_isActiveInHierarchy";
export const builtinComponentKeyName = "builtin_components";
// It's easier to use a string than a symbol here because the symbol might not be the same when imported in other packages
export const editorGuidKeyName = "needle_editor_guid";


function tryEval(str: string) {
    try {
        // https://esbuild.github.io/content-types/#direct-eval
        (0, eval)(str);
    }
    catch (err) {
        // ignore errors
        // when built with vite the strings above might be replaced with the actual variables
        // and that would then fail (e.g. NEEDLE_ENGINE_VERSION becomes 1.0.0 for example)
        if (debug)
            console.error(err);
    }
}