"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseStartConfig = void 0;
//#region imports
const lib_1 = require("tnp-core/lib");
const lib_2 = require("tnp-core/lib");
const lib_3 = require("tnp-core/lib");
const lib_4 = require("typescript-class-helpers/lib");
const index_1 = require("../../index");
const base_project_1 = require("./base-project");
class BaseStartConfig {
    //#region prepareArgs
    /**
     * @deprecated
     * use standard import / not default
     */
    static prepareArgs(cliClassArr) {
        const result = cliClassArr
            .map(c => Object.values(c))
            .reduce((a, b) => {
            return a.concat(b.map(funcOrClass => {
                return {
                    classOrFnName: lib_4.CLASS.getName(funcOrClass),
                    funcOrClass,
                };
            }));
        }, []).sort((a, b) => {
            if (a.classOrFnName < b.classOrFnName) {
                return -1;
            }
            if (a.classOrFnName > b.classOrFnName) {
                return 1;
            }
            return 0;
        });
        return result;
    }
    //#endregion
    //#region prepareFromFiles
    static prepareFromFiles(cliClassArr) {
        return this.prepareArgs(cliClassArr
            .map(c => require(lib_2.path.resolve(c)).default)
            .filter(f => lib_2._.isObject(f)));
    }
    //#endregion
    //#region fields
    argsv = process.argv;
    shortArgsReplaceConfig = {};
    functionsOrClasses = [];
    ProjectClass = base_project_1.BaseProject;
    callbackNotRecognizedCommand;
    /**
     * @deprecated
     */
    useStringArrForArgsFunctions;
    //#endregion
    //#region constructor
    constructor(options) {
        options = options ? options : {};
        for (const key in options) {
            if (Object.prototype.hasOwnProperty.call(options, key)) {
                const value = options[key];
                if (value) {
                    this[key] = value;
                }
            }
        }
        for (let index = 0; index < this.argsv.length; index++) {
            const arg = this.argsv[index];
            if (arg.endsWith('-debug-brk')) {
                this.argsv[index] = arg.replace(/\-debug\-brk$/, '');
            }
            if (arg.endsWith('-debug')) {
                this.argsv[index] = arg.replace(/\-debug$/, '');
            }
        }
        if (this.argsv?.length >= 2 &&
            (this.argsv[0].endsWith('bin/node') ||
                this.argsv[0].endsWith('bin\\node') ||
                this.argsv[0].endsWith('bin\\\\node') ||
                this.argsv[0].endsWith('\\\\node.exe') ||
                this.argsv[0].endsWith('\\node.exe'))) {
            this.argsv = this.argsv.slice(2);
        }
        const commandArgIndex = 0;
        const commandArg = this.argsv[commandArgIndex];
        if (commandArg) {
            const longerCommandVersion = this.shortArgsReplaceConfig[commandArg];
            if (longerCommandVersion) {
                this.argsv[commandArgIndex] = longerCommandVersion;
            }
        }
        let recognizedClassFnOrFunction = null;
        let restOfArgs = [];
        let methodNameToCall = undefined;
        let methodsOfRecognizedClass = [];
        let globalClassForGlobalCommands = null;
        for (const { classOrFnName, funcOrClass } of this.functionsOrClasses) {
            if (lib_2._.isFunction(funcOrClass)) {
                const classMethodsNames = lib_4.CLASS.getMethodsNames(funcOrClass).filter(f => !f.startsWith('_'));
                if (classOrFnName === '') {
                    globalClassForGlobalCommands = funcOrClass;
                }
                if (this.argsv.length === 0 && classOrFnName === '') {
                    recognizedClassFnOrFunction = funcOrClass;
                    restOfArgs = [];
                    methodNameToCall = '';
                    methodsOfRecognizedClass = classMethodsNames;
                    break;
                }
                const check = index_1.HelpersTaon.cliTool.match({
                    functionOrClassName: classOrFnName,
                    restOfArgs: lib_2._.cloneDeep(this.argsv),
                    argsReplacements: this.shortArgsReplaceConfig,
                    classMethodsNames,
                });
                if (check.isMatch) {
                    recognizedClassFnOrFunction = funcOrClass;
                    restOfArgs = lib_2._.cloneDeep(check.restOfArgs);
                    methodNameToCall = check.methodNameToCall;
                    methodsOfRecognizedClass = classMethodsNames;
                    // console.log('--- recognized command ---', { classOrFnName, classMethodsNames })
                }
            }
        }
        if (recognizedClassFnOrFunction) {
            global?.spinner?.stop();
            // console.log('--- recognized command ---', {
            //   recognizedClassFnOrFunction,
            //   methodNameToCall,
            //   restOfArgs,
            //   methodsOfRecognizedClass,
            // });
            if (lib_3.Helpers.isClass(recognizedClassFnOrFunction)) {
                // console.log('USING FROM CLASS')
                const obj = new recognizedClassFnOrFunction(index_1.HelpersTaon.cliTool.globalArgumentsParserTnp(restOfArgs, this.ProjectClass), methodNameToCall, this.ProjectClass.ins.nearestTo(process.cwd()), process.cwd(), this.ProjectClass.ins);
            }
            else {
                // console.log('USING FROM FUNCTION')
                if (this.useStringArrForArgsFunctions) {
                    recognizedClassFnOrFunction.apply({}, [
                        index_1.HelpersTaon.cliTool.globalArgumentsParserTnp(restOfArgs, this.ProjectClass)
                            .split(' '),
                    ]);
                }
                else {
                    recognizedClassFnOrFunction.apply({}, [
                        index_1.HelpersTaon.cliTool.globalArgumentsParserTnp(restOfArgs, this.ProjectClass),
                    ]);
                }
            }
            process.stdin.resume();
        }
        else {
            if (lib_2._.isFunction(this.callbackNotRecognizedCommand)) {
                // console.log(`this.argsv `, this.argsv)
                this.callbackNotRecognizedCommand({
                    firstArg: lib_2._.first(this.argsv),
                    runGlobalCommandByName: (commandName) => {
                        if (globalClassForGlobalCommands) {
                            const obj = new globalClassForGlobalCommands(index_1.HelpersTaon.cliTool.globalArgumentsParserTnp(this.argsv, this.ProjectClass), commandName, this.ProjectClass.ins.nearestTo(process.cwd()), process.cwd(), this.ProjectClass.ins);
                        }
                        else {
                            lib_3.Helpers.error(`Global class for global commands not found`, false, true);
                        }
                    },
                });
            }
            else {
                lib_3.Helpers.error(`[${lib_1.config.frameworkName}] Command not recognized`, false, true);
            }
        }
    }
}
exports.BaseStartConfig = BaseStartConfig;
//# sourceMappingURL=base-start-config.backend.js.map