import { TaonBaseContext, Taon__NS__createContext } from 'taon/lib-prod';
import { crossPlatformPath, config, tnpPackageName, ___NS__kebabCase, Helpers__NS__info, Helpers__NS__logInfo, Helpers__NS__logWarn, Helpers__NS__removeFileIfExists, Utils__NS__getFreePort } from 'tnp-core/lib-prod';
import { DevBuildContext } from './dev-build.abstract.context';
import { DevBuildController } from './dev-build.controller';
import { DevBuildModels__NS__START_PORT_BUID_PROCESS } from './dev-build.models';
import { DevBuildRepository } from './dev-build.repository';
//namespace DevBuildUtils
export const DevBuildUtils__NS__context = Taon__NS__createContext(() => ({
    contextName: `ProjectActionContext`,
    contexts: { TaonBaseContext, DevBuildContext },
    database: false,
    kv_database: {
        dbLocationFn: ({ cwd, port, baseLocation, contextName, repositoryClassName, }) => {
            return crossPlatformPath([
                baseLocation,
                ___NS__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();
export const DevBuildUtils__NS__startAcionWorker = async () => {
    //#region @backendFunc
    const currentActionPort = await Utils__NS__getFreePort({
        startFrom: DevBuildModels__NS__START_PORT_BUID_PROCESS,
    });
    const workerMainContext = DevBuildUtils__NS__context.cloneAsNormal({
        overrideHost: `http://localhost:${currentActionPort}`,
    });
    const wokerMainContextRef = await workerMainContext.initialize({
    // onlyMigrationRun,
    });
    contexts.set(currentActionPort, wokerMainContextRef);
    Helpers__NS__logInfo(`Server started`);
    const devBuildController = await wokerMainContextRef.getInstanceBy(DevBuildController);
    const devBuildRepository = await wokerMainContextRef.getInstanceBy(DevBuildRepository);
    const exitProgramCleaningFn = () => {
        return new Promise(async (resolve) => {
            const allWorkers = devBuildRepository.allProjectsInProcess();
            for (const buildProj of allWorkers) {
                try {
                    Helpers__NS__logInfo(`Deleting from pool ${buildProj.nameForNpmPackage} ${buildProj.port} ${buildProj.location}`);
                    await devBuildRepository.deleteFromPool(buildProj);
                }
                catch (error) {
                    config.frameworkName === tnpPackageName && console.error(error);
                    Helpers__NS__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) {
                    config.frameworkName === tnpPackageName && console.error(error);
                    Helpers__NS__logWarn(`Not able to delete destry context for ${buildProj.nameForNpmPackage} ` +
                        `(port=${buildProj.port})`);
                }
            }
            Helpers__NS__info('Taon Build Exit Cleaning Done');
            Helpers__NS__removeFileIfExists(devBuildRepository.jsonDbLocation);
            resolve();
        });
    };
    return {
        devBuildController,
        devBuildRepository,
        exitProgramCleaningFn,
        currentActionPort,
    };
    //#endregion
};
//end of namespace DevBuildUtils
//# sourceMappingURL=dev-build.utils.js.map