
/**
 *  Check the node version to be make sure user installed wavemaker supported node.
 *  Generate the angular app with codegen.
 *  Check the existing npm packages, if doesn't exist download and install npm packages.
 *  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
 *   
 */
const fs = require('fs');
const { downloadNPMPackage } = require('./download-packages');

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



const init = () => {
    // To check the node version.
    checkNodeVersion();

    // To generate the angular app with codegen
    executeSyncCmd('node  ' + args.codegenPath + 'generate-angular-app.js ' + buildArgs(), null, MSG_CODEGEN_LOG);

    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

    }
    // Download app-ng-runtime node modules
   let pathCodegePackage = downloadNPMPackage(packageInfo);

    try {
        // Symlink to reuse the existing node_modules
        fs.symlinkSync(pathCodegePackage + '/node_modules', args.appTarget + '/node_modules', 'dir');
    } catch (err) {
        console.log(MSG_NG_RUNTIME_LOG + 'FAILED the symlink for the node_modules', err);
        process.exit(err.code || err.pid);
    }

    // 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);


}

init();
