/* 
 gulpfile.js made by xueboren.
 just for gulp.
*/
var gulp = require("gulp");
var $ = require("gulp-load-plugins")();
//var runSequence = require("gulp-run-sequence");
var merge = require('event-stream').merge;
var argv = require('yargs').argv;
var os = require("os");
var fs = require("fs");

// $.htmlReplace

var config = {
  src_index: 'app/index.html',
  src_htmlDir: 'app/html',
  src_cssDir: 'app/css',
  src_jsDir: 'app/js',
  src_imageDir: 'app/img',
  src_libDir: 'app/lib',
  src_serverDir: 'app/scripts',
  dist_index: 'index.html',
  dist_htmlDir: 'html',
  dist_cssDir: 'css',
  dist_jsDir: 'js',
  dist_imageDir: 'img',
  dist_libDir: 'lib',
  dist_serverDir: 'scripts',
  destDir: 'dist',
  templates_js_file: 'templates.js',
  templates_js_min_file: 'templates.min.js',
  all_js_file: 'app-all.js',
  all_js_min_file: 'app-all.min.js',
  all_css_file: 'app-all.css',
  all_css_min_file: 'app-all.min.css'
};

gulp.task("copy-lib", function(){
  gulp.src("app/lib/ionic/release/**")
      .pipe(gulp.dest(config.destDir+"/"+config.dist_libDir+"/ionic/"));
});
gulp.task("copy-server", function(){
  gulp.src(config.src_serverDir+"/**/*.*")
    .pipe(gulp.dest(config.destDir+"/"+config.dist_serverDir));
});
gulp.task("handle-image", function(){
  return gulp.src(config.src_imageDir+"/*.*")
        .pipe(gulp.dest(config.destDir+"/"+config.dist_imageDir));
});

gulp.task("handle-js", ["template-to-js"], function(){
  gulp.src([config.src_jsDir+"/*.js","!templates.js"])
        .pipe($.uglify({
          mangle: false,
          preserveComments: function(node, comment) {
                return comment.line === 0; //min.js文件取消所有 注释 
              }
        }))
        .pipe($.concat(config.all_js_min_file))
        .pipe(gulp.dest(config.destDir+"/"+config.dist_jsDir)),
      gulp.src(config.src_jsDir+"/*.js")
        .pipe($.concat(config.all_js_file))
        .pipe(gulp.dest(config.destDir+"/"+config.dist_jsDir));
});

gulp.task("handle-css", function(){
  gulp.src(config.src_cssDir+"/*.css")
        .pipe($.concat(config.all_css_file))
        .pipe(gulp.dest(config.destDir+"/"+config.dist_cssDir)),
  gulp.src(config.src_cssDir+"/*.css")
        .pipe($.minifyCss())
        .pipe($.concat(config.all_css_min_file))
        .pipe(gulp.dest(config.destDir+"/"+config.dist_cssDir));
});
gulp.task("handle-html", function(){
  return gulp.src(config.src_htmlDir+"/*.html")
        .pipe($.minifyHtml({
          empty: true,
          quotes: true,
          conditionals: true,
          spare: true
        }))
        .pipe(gulp.dest(config.destDir+"/"+config.dist_htmlDir));
});
gulp.task("handle-index", function(){
  gulp.src(config.src_index)
        .pipe($.htmlReplace({
          'lib_js': 'lib/ionic/js/ionic.bundle.min.js',
          'lib_css': 'lib/ionic/css/ionic.min.css',
          'css': 'css/'+config.all_css_min_file,
          'js': ['js/'+config.templates_js_min_file, 'js/'+config.all_js_min_file]
        }))
        .pipe($.minifyHtml({
          empty: true,
          quotes: true,
          conditionals: true,
          spare: true
        }))
        .pipe(gulp.dest(config.destDir));
});

gulp.task("template-to-js", function (){
  gulp.src('app/templates/**/*.html')
    .pipe($.html2js({
      base: 'app/templates/',
      outputModuleName: 'boren-templates',
      useStrict: true
    }))
    .pipe($.concat(config.templates_js_file))
    .pipe($.header("/** 项目相关的angular模板,以JS方式来提供 **/"))
    .pipe(gulp.dest(config.destDir+"/"+config.dist_jsDir))
    .pipe($.uglify({
      mangle: false,
      preserveComments: function(node, comment) {
        return comment.line === 0; //min.js文件取消所有 注释 
      }
    }))
    .pipe($.concat(config.templates_js_min_file))
    .pipe(gulp.dest(config.destDir+"/"+config.dist_jsDir));
});

gulp.task("clean", function(){
  return gulp.src(config.destDir)
      .pipe($.clean());
});

gulp.task("build",function(callback){
  $.runSequence(
    "clean",
    "copy-lib",
    "handle-image",
    "template-to-js",
    ["handle-js", "handle-css", "handle-html"],
    "handle-index",
    "copy-server",
    callback
  );
});

gulp.task("default",["build"]);



///////////////////////////
// Test 
///////////////////////////
//gulp.task('webdriver-update', $.protractor.webdriver_update);
// webdriver-download
gulp.task('webdriver-download', function() {
  var chromeDriverUrl,
    platform = os.platform();

  var destDir = __dirname + '/.selenium/';

  // Only download once.
  if (fs.existsSync(destDir + '/chromedriver') || fs.existsSync(destDir + '/chromedriver.exe')) {
    return gulp.src('');
  }

  if (platform === 'linux') {
    chromeDriverUrl = 'http://chromedriver.storage.googleapis.com/2.12/chromedriver_linux64.zip'; 
  }
  else if (platform === 'darwin') {
    chromeDriverUrl = 'http://chromedriver.storage.googleapis.com/2.14/chromedriver_mac32.zip';
  }
  else {
    chromeDriverUrl = 'http://chromedriver.storage.googleapis.com/2.14/chromedriver_win32.zip';
  }
  //console.log(__dirname+"    "+destDir+"    "+chromeDriverUrl);
  var selenium = $.download('https://selenium-release.storage.googleapis.com/2.45/selenium-server-standalone-2.45.0.jar')
    .pipe(gulp.dest('temp'));
  //console.log(selenium);

  //var chromedriver = $.download(chromeDriverUrl)
    //.pipe($.unzip())
    //.pipe($.chmod(755))
    //.pipe(gulp.dest(destDir));

    console.log("-------- over --------");
    return selenium;
  //return merge(selenium, chromedriver);
});

gulp.task("e2e-test", ['webdriver-download'], function(){
  var port = 8081;
  $.connect.server({
    root: __dirname,
    port: port
  });
  var conf = {
    configFile: 'protractor.conf.js',
    args: [
      '--baseUrl', 'http://127.0.0.1:'+port,
      '--seleniumServerJar', __dirname + '/.selenium/selenium-server-standalone-2.45.0.jar',
      '--chromeDriver', __dirname + '/.selenium/chromedriver'
    ]
  };
  var specs = argv.specs ?
    argv.specs.split(',').map(function(s) { return s.trim(); }) :
    ['test/e2e/**/*.js'];

  return gulp.src(specs)
    .pipe($.protractor.protractor(conf))
    .on('error', function(e) {
      console.log(e)
      $.connect.serverClose();
    })
    .on('end', function() {
      $.connect.serverClose();
    });
});

gulp.task("test", ["e2e-test"]);