
/**
 *  Download and install the app-ng-runtime package
 *  Run the build and post build for the generated angular app.
 *  
 *  CONSOLE ARGUMENTS:-
 *  nodeVMArgs:String: Node environment params  (Eg: '--max-old-space-size=2040')
 *  ngBuildParams:String: Anglar build params (Eg: '--prod=true --source-map=false')
 *  runtimeUIVersion:String: Runtime version (Eg: 10.6.6-next.10243)
 *  appSrc:String: Source folder to generate the angular app (current directory Eg: '.')
 *  appTarget:String: Target folder to save the generated app (Eg: 'target/ui-build/generated-app')
 *  codegenPath:String: Input to the codegen-CLI -->  Codegen installation path to copy the angular-template-app
 *  optimizeUIBuild : By default this flag will be true. If it's windows platform we are making the flag to false, it means no optimisation for windows.
 */
const fs = require('fs');
const { downloadNPMPackage } = require('./download-packages');

const { executeSyncCmd, args, MSG_NG_RUNTIME_LOG, MSG_NG_RUNTIME_SUCCESS } = require('./build-util');



/**
 * Download the app runtime package
 * Symlink to reuse the existing node modules (If windows optimizeUIBuild will be false and install all node modules every build )
 * Run the ng build and post build for the project
 */
const init = () => {

    let packageInfo = {
        name: 'app-ng-runtime',
        version: args.runtimeUIVersion,
        packageJsonFile: args.codegenPath + '/angular-app/package.json',
        successMsg: MSG_NG_RUNTIME_SUCCESS,
        infoMsg: MSG_NG_RUNTIME_LOG

    }
       
        try {
        // Symlink to reuse the existing node_modules
        if(args.optimizeUIBuild === 'true') {
         // Download app-ng-runtime node modules
          let pathNGRuntimePackage = downloadNPMPackage(packageInfo);
          fs.symlinkSync(pathNGRuntimePackage + '/node_modules', args.appTarget + '/node_modules', 'dir');
        } else {
            fs.copyFileSync(packageInfo.packageJsonFile, args.appTarget + '/package.json');
            executeSyncCmd('cd ' + args.appTarget + ' && npm install', null, MSG_NG_RUNTIME_LOG);  
        }
    } catch (err) {
        console.log(MSG_NG_RUNTIME_LOG + 'FAILED the symlink for the node_modules', err);
        process.exit(err.code || err.pid);
    }

    const NG_BUILD_MSG = 'NG BUILD MIGHT HAVE FAILED WITH HEAP OUT OF MEMORY, RE-EXECUTE THE BUILD BY INCREASING THE MAX-OLD-SPACE-SIZE ARGUMENT VALUE FOR BUILD.UI.NODE.ARGS PROPERTY IN DEPLOYMENT PROFILE';
    // Generating the angular build and post build process.
    executeSyncCmd('cd ' + args.appTarget + ' && node ' + args.nodeVMArgs + ' ' + './node_modules/@angular/cli/bin/ng build ' + args.ngBuildParams + ' && node build-scripts/post-build.js', null, MSG_NG_RUNTIME_LOG, false, NG_BUILD_MSG);


}

init();
