// Copyright & License details are available under JXCORE_LICENSE file

var fs = require('fs');
var path = require('path');
var jxtools = require('jxtools');
var fname = 'io.jxcore.node.jx';
var dname = 'io.jxcore.node';


exports.run = function () {

  if (process.argv[2] !== 'sample')
    return;

  process.argv[2] = '--sample';
  var parsedArv = jxcore.utils.argv.parse({force: true});

  exports.useSample(parsedArv.sample.value)
};



exports.useSample = function(sampleName) {

  var dir = path.resolve(sampleName);
  if (!fs.existsSync(dir))
    dir = path.join(process.cwd(), dname, 'sample', sampleName);

  if (!fs.existsSync(dir)) {
    jxcore.utils.console.error('Wrong sample name:', sampleName);
    return;
  }

  if (path.basename(dir) !== 'www')
    dir = path.join(dir, 'www');

  var www = path.join(process.cwd(), "www");
  var backup_www = path.join(process.cwd(), "www_backup");

  if (!fs.existsSync(backup_www)) {
    jxtools.fs.copySync(www, backup_www);
  }

  jxtools.fs.rmdirSync(www);
  jxtools.fs.copySync(dir, www);

  jxcore.utils.cmdSync('cordova prepare');

  jxcore.utils.console.info('Using `' + sampleName + '` sample.');
};
@@ -434,17 +434,16 @@
 e)%0A%7D;%0A%0A%0A
-%0A
 exports.
@@ -462,16 +462,17 @@
 function
+ 
 (sampleN
@@ -986,113 +986,906 @@
 %0A%0A  
-jxtools.fs.rmdirSync(www
+var commands = %5B%5D;%0A%0A  var package_json = path.join(dir, %22jxcore/package.json%22);%0A  var node_modules = path.join(dir, %22jxcore/node_modules%22);%0A%0A  if (fs.existsSync(package_json) && !fs.existsSync(node_modules)) %7B%0A    commands.push(%7B%0A      name: %22install modules%22,%0A      command: '%22' + process.execPath + '%22 install',%0A      cwd: path.join(dir, 'jxcore'),%0A      caption: 'Installing node modules for the sample...'%0A    %7D);%0A  %7D%0A%0A  commands.push(%7B%0A    name: 'remove_dir',%0A    command: jxtools.fs.getRmdirCommand(www),%0A    caption: 'Removing previous www folder...'%0A  %7D
 );%0A
+%0A
   
-jxtools.fs.copySync(dir, www);%0A%0A  jxcore.utils.cmdSync('cordova prepare');%0A%0A
+commands.push(%7B%0A    name: 'copy_sample',%0A    command: function () %7B%0A      jxtools.fs.copySync(dir, www);%0A    %7D,%0A    caption: 'Copying sample folder...'%0A  %7D);%0A%0A  commands.push(%7B%0A    name: 'cordova_prepare',%0A    command: 'cordova prepare',%0A    caption: 'Executing %60cordova prepare%60 command...'%0A  %7D);%0A%0A  commands.push(function () %7B%0A  
   jx
@@ -1913,9 +1913,24 @@
 fo('
-U
+The project is i
 sing
@@ -1961,11 +1961,148 @@
 mple
-.');
+ now.');%0A  %7D);%0A%0A  jxtools.fs.execMultiple(commands, function (ret) %7B%0A    if (ret.errors)%0A      jxcore.utils.console.error(ret.errors);%0A  %7D);%0A
 %0A%7D;

use async commands