"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DevBuildUtils = void 0;
const lib_1 = require("taon/lib");
const lib_2 = require("tnp-core/lib");
const dev_build_abstract_context_1 = require("./dev-build.abstract.context");
const dev_build_controller_1 = require("./dev-build.controller");
const dev_build_models_1 = require("./dev-build.models");
const dev_build_repository_1 = require("./dev-build.repository");
var DevBuildUtils;
(function (DevBuildUtils) {
    DevBuildUtils.context = lib_1.Taon.createContext(() => ({
        contextName: `ProjectActionContext`,
        contexts: { TaonBaseContext: lib_1.TaonBaseContext, DevBuildContext: dev_build_abstract_context_1.DevBuildContext },
        database: false,
        kv_database: {
            dbLocationFn: ({ cwd, port, baseLocation, contextName, repositoryClassName, }) => {
                return (0, lib_2.crossPlatformPath)([
                    baseLocation,
                    lib_2._.kebabCase(cwd.replace(/\./g, '___')), // each cwd and proces has diffrent db
                    `kv_${contextName}__${repositoryClassName}___port${port}.json`,
                ]);
            },
        },
        logs: {
        // routes: true,
        // db: true,
        },
        disabledRealtime: true,
        skipWritingServerRoutes: true,
    }));
    const contexts = new Map();
    DevBuildUtils.startAcionWorker = async () => {
        //#region @backendFunc
        const currentActionPort = await lib_2.Utils.getFreePort({
            startFrom: dev_build_models_1.DevBuildModels.START_PORT_BUID_PROCESS,
        });
        const workerMainContext = DevBuildUtils.context.cloneAsNormal({
            overrideHost: `http://localhost:${currentActionPort}`,
        });
        const wokerMainContextRef = await workerMainContext.initialize({
        // onlyMigrationRun,
        });
        contexts.set(currentActionPort, wokerMainContextRef);
        lib_2.Helpers.logInfo(`Server started`);
        const devBuildController = await wokerMainContextRef.getInstanceBy(dev_build_controller_1.DevBuildController);
        const devBuildRepository = await wokerMainContextRef.getInstanceBy(dev_build_repository_1.DevBuildRepository);
        const exitProgramCleaningFn = () => {
            return new Promise(async (resolve) => {
                const allWorkers = devBuildRepository.allProjectsInProcess();
                for (const buildProj of allWorkers) {
                    try {
                        lib_2.Helpers.logInfo(`Deleting from pool ${buildProj.nameForNpmPackage} ${buildProj.port} ${buildProj.location}`);
                        await devBuildRepository.deleteFromPool(buildProj);
                    }
                    catch (error) {
                        lib_2.config.frameworkName === lib_2.tnpPackageName && console.error(error);
                        lib_2.Helpers.logWarn(`Not able to delete project from main worker projecs pool`);
                    }
                }
                for (const buildProj of allWorkers) {
                    try {
                        await contexts.get(Number(buildProj.port)).destroy();
                    }
                    catch (error) {
                        lib_2.config.frameworkName === lib_2.tnpPackageName && console.error(error);
                        lib_2.Helpers.logWarn(`Not able to delete destry context for ${buildProj.nameForNpmPackage} ` +
                            `(port=${buildProj.port})`);
                    }
                }
                lib_2.Helpers.info('Taon Build Exit Cleaning Done');
                lib_2.Helpers.removeFileIfExists(devBuildRepository.jsonDbLocation);
                resolve();
            });
        };
        return {
            devBuildController,
            devBuildRepository,
            exitProgramCleaningFn,
            currentActionPort,
        };
        //#endregion
    };
})(DevBuildUtils || (exports.DevBuildUtils = DevBuildUtils = {}));
//# sourceMappingURL=dev-build.utils.js.map