"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseNpmHelpers = 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("tnp-core/lib");
const lib_5 = require("tnp-core/lib");
const base_bower_json_1 = require("./base-bower-json");
const base_feature_for_project_1 = require("./base-feature-for-project");
const base_node_modules_1 = require("./base-node-modules");
const base_package_json_1 = require("./base-package-json");
//#endregion
class BaseNpmHelpers extends base_feature_for_project_1.BaseFeatureForProject {
    //#region fields
    packageJson;
    _packageJsonType = base_package_json_1.BasePackageJson;
    _packageJsonTypeOriginal = base_package_json_1.BasePackageJson;
    nodeModules;
    _nodeModulesType = base_node_modules_1.BaseNodeModules;
    __nodeModulesTypeOriginal = base_node_modules_1.BaseNodeModules;
    bowerJson;
    //#endregion
    //#region constructor
    constructor(project) {
        super(project);
        this.project = project;
        if (this._packageJsonType === this._packageJsonTypeOriginal) {
            this.packageJson = new this._packageJsonType({ cwd: project.location });
        }
        if (this._nodeModulesType === this.__nodeModulesTypeOriginal) {
            this.nodeModules = new this._nodeModulesType(project.location, this);
        }
        this.bowerJson = new base_bower_json_1.BaseBowerJson(project.location);
    }
    //#endregion
    //#region prefer yarn over npm
    preferYarnOverNpm() {
        return false;
    }
    //#endregion
    //#region reset package-lock.json
    async resetPackageLockJson() {
        //#region @backendFunc
        const children = this.project.children;
        const currentLocation = this.project.location;
        children.forEach(c => {
            lib_5.Helpers.info(`reverting changes of package-lock.json for ${lib_3.chalk.bold(c.name)}`);
            // console.log(`Project ${c.name} - loc: ${c.location} `)
            try {
                this.project
                    .run(`git checkout ${c.location.replace(currentLocation + '/', '')}/package-lock.json`)
                    .sync();
            }
            catch (error) { }
        });
        lib_5.Helpers.info('RESETING DONE');
        //#endregion
    }
    //#endregion
    //#region start npm task
    startNpmTask(taskName, additionalArguments) {
        //#region @backendFunc
        if (lib_4._.isObject(additionalArguments)) {
            additionalArguments = Object.keys(additionalArguments)
                .map(k => `--${k} ${additionalArguments[k]}`)
                .join(' ');
        }
        const command = `npm run ${taskName} ${additionalArguments ? ' -- ' + additionalArguments : ''}`;
        lib_5.Helpers.info(`Starting npm task: "${command}"`);
        return this.project.run(command, {
            output: true,
            biggerBuffer: true,
        });
        //#endregion
    }
    //#endregion
    //#region check if logged in to registry
    /**
     *
     * @param registry without specified registr is checking npm registry
     * @returns
     */
    async isLoggedInToRegistry(registry) {
        //#region @backendFunc
        // validate registry with regex
        lib_5.Helpers.info(`Checking if logged in to registry: ${registry || '< default public npm >'} .... `);
        if (registry && registry.match(/^(https?:\/\/)?([a-z0-9-]+\.?)+(:\d+)?$/)) {
            throw new Error(`Invalid registry: ${registry}`);
        }
        const registryLink = registry ? `--registry=${registry}` : '';
        return new Promise((resolve, reject) => {
            const command = `npm whoami ${registryLink}`;
            console.log(`Executing command: ${command}`);
            lib_3.child_process.exec(command, { cwd: this.project.location }, (error, stdout, stderr) => {
                if (error) {
                    if (stderr.includes('ENEEDAUTH')) {
                        resolve(false);
                    }
                    else {
                        resolve(false); // TODO QUICK FIX
                    }
                }
                else {
                    resolve(true);
                }
            });
        });
        //#endregion
    }
    //#endregion
    //#region login to registry
    /**
     * Prompt the user to log in to a specific npm registry.
     * @param {string} [registry] - Optional npm registry URL.
     * @returns {Promise<void>} - A promise that resolves when the login process completes.
     */
    async loginToRegistry(registry) {
        //#region @backendFunc
        lib_5.Helpers.info(`Trying to login to npm registry: ${registry || '< default public npm >'}`);
        return new Promise((resolve, reject) => {
            const args = ['login'];
            if (registry) {
                args.push(`--registry=${registry}`);
            }
            const child = lib_3.child_process.spawn('npm', args, {
                stdio: 'inherit',
                shell: true, // ensures compatibility with Git Bash on Windows
            });
            child.on('exit', code => {
                if (code === 0) {
                    resolve();
                }
                else {
                    reject(new Error(`npm login failed with exit code ${code}`));
                }
            });
            child.on('error', err => {
                reject(err);
            });
        });
        //#endregion
    }
    //#endregion
    //#region check if logged in to npm
    async makeSureLoggedInToNpmRegistry(registry) {
        //#region @backendFunc
        while (true) {
            let loggedIn = await this.isLoggedInToRegistry();
            if (loggedIn) {
                lib_5.Helpers.info(`You logged in to npm registry=${registry || '< default public npm >'}`);
                break;
            }
            await lib_2.UtilsTerminal.pressAnyKeyToContinueAsync({
                message: `
        NPM REGISTRY: ${!registry ? '< default public npm >' : registry}

You are not logged in to npm. Press any key and follow instructions...`,
            });
            try {
                if (!!registry) {
                    lib_5.Helpers.info(`Enter you npm credentials for registry: ${registry}`);
                }
                await this.loginToRegistry();
            }
            catch (error) { }
        }
        //#endregion
    }
    //#endregion
    //#region should release lib
    async shouldReleaseMessage(options) {
        //#region @backendFunc
        options = options || {};
        options.actionType = options.actionType || 'release';
        const { releaseVersionBumpType: releaseVersionType, versionToUse, whatToRelease: { children: releaseChildren, itself: releaseItself }, skipQuestionToUser, children, } = options;
        const itselfString = `- this project: ${lib_3.chalk.italic(this.project.nameForNpmPackage)}` +
            `@${lib_3.chalk.bold(versionToUse ? versionToUse : this.project.packageJson.getBumpedOrCurrentVersionFor(releaseVersionType))}`;
        const childrenToRelease = children ? children : this.project.children;
        const childrenString = `- all (${childrenToRelease.length}) children projects: ${lib_3.chalk.italic((children ? children : this.project.children)
            .map(c => `${c.nameForNpmPackage}` +
            `@${lib_3.chalk.bold(c.packageJson.getBumpedOrCurrentVersionFor(releaseVersionType))}`)
            .join(', '))}`;
        let projectsInfo = '';
        if (releaseItself && releaseChildren) {
            projectsInfo = `${itselfString}\n${childrenString}`;
        }
        else if (!releaseItself && releaseChildren) {
            projectsInfo = `${childrenString}`;
        }
        else if (releaseItself && !releaseChildren) {
            projectsInfo = `${itselfString}`;
        }
        lib_5.Helpers.info(`
${options.messagePrefix ? `[${options.messagePrefix}] ` : `\t`}Projects to ${options.actionType}:
${projectsInfo}
      `);
        let message = `${options.messagePrefix ? `[${options.messagePrefix}] ` : ``}Proceed with ${options.actionType} ?`;
        return skipQuestionToUser
            ? true
            : await lib_2.UtilsTerminal.confirm({ message, defaultValue: true });
        //#endregion
    }
    //#endregion
    //#region publish to npm registry
    /**
     * @param registry when not specified, it will use the default npm registry
     */
    async publishToNpmRegistry(options) {
        //#region @backendFunc
        const { registry } = options || {};
        while (true) {
            const accessPublic = this.packageJson.name.startsWith('@') && !this.packageJson.isPrivate
                ? '--access public'
                : '';
            const registryOpt = registry ? `--registry ${registry}` : '';
            const commandForPublish = `npm publish ${registryOpt} ${accessPublic}`;
            lib_5.Helpers.info(`

      Package: ${this.packageJson.name}
      Command for publish: ${commandForPublish}
      cwd: ${this.project.location}

      `);
            try {
                await lib_1.UtilsExecProc.spawnAsync(commandForPublish, {
                    cwd: this.project.location,
                    shell: true,
                }).waitUntilDoneOrThrow();
                break;
            }
            catch (error) {
                console.log(error);
                lib_5.Helpers.error(`

        Not able to publish to npm registry project in ${this.project.location}

        `, true, true);
                const choices = {
                    again: {
                        name: 'Try again publish',
                    },
                    skip: {
                        name: 'Skip publishing this porject',
                    },
                    exit: {
                        name: 'Exit program',
                    },
                };
                const selected = await lib_2.UtilsTerminal.select({
                    choices,
                });
                if (selected === 'again') {
                    continue;
                }
                if (selected === 'skip') {
                    break;
                }
                if (selected === 'exit') {
                    process.exit(0);
                }
            }
        }
        //#endregion
    }
    //#endregion
    //#region get package version from npm registry
    getPackageVersionFromNpmRegistry(packageName, options) {
        //#region @backendFunc
        return new Promise((resolve, reject) => {
            const { registry } = options || {};
            const registryOpt = registry ? `--registry ${registry}` : '';
            lib_3.child_process.exec(`npm view ${packageName} version ${registryOpt}`, { cwd: this.project.location }, (error, stdout, stderr) => {
                if (error) {
                    reject(new Error(stderr));
                }
                else {
                    resolve(stdout.trim());
                }
            });
        });
        //#endregion
    }
}
exports.BaseNpmHelpers = BaseNpmHelpers;
//# sourceMappingURL=base-npm-helpers.js.map