const fs = require('fs');
const { executeSyncCmd } = require('./build-util');
const os = require('os');
const path = require('path');


/**
 *  To check the npm package installation successs or not
 * @param {*} path  File path where installation success message was written
 * @param {*} msg   Success messsage to confirm that package was installed
 * @returns boolean true/false
 */
const isNPMPackageExist = (path, msg) => {
    if (fs.existsSync(path)) {
        const successMsg = fs.readFileSync(path, { encoding: 'utf8', flag: 'r' });
        if (successMsg == msg) {
            return true;
        }

    } else {
        return false;
    }
}

/**
 *  Check  node modules package were installed or not
 *  Create dir for  packages with the version name
 *  Copy the generated angular app package.json to PATH_NPM_PACKAGE folder
 *  Run npm install
 *  Write  success file to be make sure it was installed successfully.
 */
const downloadNPMPackage = (packageInfo) => {
    const HOME_DIR = os.homedir();
    const PATH_NPM_PACKAGE = (packageInfo.baseDir || HOME_DIR + '/.wm/node_modules/') + packageInfo.name + '/' + packageInfo.version;
    const PATH_NPM_PACKAGE_SUCCESS = PATH_NPM_PACKAGE + '/.SUCCESS';
    let isError = false;

    // To check global app runtime node modules.
    if (!isNPMPackageExist(PATH_NPM_PACKAGE_SUCCESS, packageInfo.successMsg)) {
        fs.mkdirSync(PATH_NPM_PACKAGE, { recursive: true });
        let npmInstallCMD = 'npm install --legacy-peer-deps ';
        if (packageInfo.packageJsonFile && fs.existsSync(packageInfo.packageJsonFile)) {
            fs.copyFileSync(packageInfo.packageJsonFile, PATH_NPM_PACKAGE + '/package.json');
            try {
                //expecting this lock file to be present for exact versions to be downloaded from private registry
                fs.copyFileSync(`${path.dirname(packageInfo.packageJsonFile)} + /package-lock.json`, `${PATH_NPM_PACKAGE} + /package-lock.json`);
            } catch (err) {
                if (err.code === 'ENOENT') {
                    console.error(`Info: package-lock.json file not found at ${path.dirname(packageInfo.packageJsonFile)}`);
                }
            }
        } else {
            npmInstallCMD = 'npm init -y &&  ' + npmInstallCMD + packageInfo.scope + '/' + packageInfo.name + '@' + packageInfo.version;
        }

        executeSyncCmd('cd ' + PATH_NPM_PACKAGE + ' && ' + npmInstallCMD, (errMsg) => {
            isError = true;
            console.log(packageInfo.infoMsg + ' Something wrong with npm installation ', errMsg);
        },  packageInfo.infoMsg);

        //only create a .SUCCESS file when there is no error
        if(!isError) {
            isError = false;
            fs.writeFileSync(PATH_NPM_PACKAGE_SUCCESS, packageInfo.successMsg);
        }

    } else {
        console.log(packageInfo.infoMsg + ' Node packages already installed!');
    }

    return PATH_NPM_PACKAGE;

}


module.exports = {
    downloadNPMPackage
}
