//var wrench = require('wrench');
var gulp = require('gulp');
var del = require('del');
var path = require('path');
var fs = require('fs');
var gutil = require('gulp-util');
var minimist = require('minimist');
var less = require('gulp-less');
var minifyCss = require('gulp-minify-css');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var footer = require('gulp-footer');
var webpack = require('webpack-stream');
var wb = require('webpack');
var webserver = require('gulp-webserver');
var replace = require('gulp-replace');
var babel = require('gulp-babel');
var es2015 = require('babel-preset-es2015');
var gulpif = require('gulp-if');

var basePath = process.env.PJ_PATH;
//var absPath = 'http://127.0.0.1:8080/efunbox-to-b/1.0.0';
var absPath = 'http://lj-web.api.ai160.com/build';

//var absPath = 'http://2blj.api.ai160.com/build';
//var absPath = 'http://114.215.119.26:80/efunbox-to-b/1.0.0';
var pkg = {}
//兼容
if(fs.existsSync(path.join(basePath, 'src/package.json'))){
  pkg = require(path.join(basePath, 'src/package.json'))
}else{
  pkg = require(path.join(basePath, 'package.json'))
  fs.writeFileSync(path.join(basePath, 'src/package.json'), fs.readFileSync(path.join(basePath, 'package.json'), 'utf-8'), 'utf-8');
  fs.unlinkSync(path.join(basePath, 'package.json'));
}

//moye配置
var moyeConf = fs.existsSync(path.join(basePath, 'moye.json')) ? require(path.join(basePath, 'moye.json')) : {}

//js uglify config
var uglifyConf = {
  compress: {
    drop_console: true
  },
  output:{
    ascii_only:true
  }
}

//server端口号
var port = minimist(process.argv.slice(2), {string: 'port'}).port;
var serverWatch = eval(minimist(process.argv.slice(3), {string: 'watch'}).watch);
var isUglify = eval(minimist(process.argv.slice(3), {string: 'uglify'}).uglify);
//老版本兼容
process.env.C_PATH = fs.existsSync(path.join(basePath, 'src/stage')) ? 'stage' : 'page'

// 获取stage列表
var stages = []
fs.readdirSync(path.join(basePath, 'src/'+process.env.C_PATH)).forEach(function(item){
  if(fs.statSync(path.join(basePath, 'src/'+process.env.C_PATH+'/'+item)).isDirectory())  stages.push(item)
});

var entry = {};
for (var i = 0; i < stages.length; i++) {
  var exists = fs.existsSync(path.join(basePath, 'src/'+process.env.C_PATH+'/' + stages[i] + '/index.js'));
  if (exists) {
    entry[stages[i]] = path.join(basePath, 'src/'+process.env.C_PATH+'/') + stages[i] + '/index.js';
  }
}

// 获取template列表
var templates = []
fs.readdirSync(path.join(basePath, 'src/res/tpl')).forEach(function(item){
  if(!fs.statSync(path.join(basePath, 'src/res/tpl/'+item)).isDirectory() && /(\.tpl)$|(\.jade)$|(\.juicer)$|(\.ejs)$/g.test(item))  templates.push(item)
});

var templates_entry = {};
for (var i = 0; i < templates.length; i++) {
  var exists = fs.existsSync(path.join(basePath, 'src/res/tpl/' + templates[i]));
  if (exists) {
    entry[templates[i]] = path.join(basePath, 'src/res/tpl/') + templates[i];
  }
}

//webpack配置
var webpackConf = function(entry, buidPath){
  var conf = {
    cache: true,
    entry: entry,
    output: {
      path: path.join(basePath, './build/' + buidPath),
      filename:'[name].js',
      chunkFilename: 'module.[name].js'
    },
    module: {
      loaders: [{
        test: /\.js$/,
        loader: 'babel'
      },{
        test: /\.jade$/,
        loader: 'jade-loader'
      },{
        test: /\.ejs$/,
        loader: 'ejs-loader'
      },{
        test: /\.tpl$/,
        loader: 'tpl-loader'
      },{
        test: /\.juicer$/,
        loader: 'juicer-loader'
      },{
        test: /\.json$/,
        loader: 'json-loader'
      }],
    },
    resolveLoader: {
      root:[
        path.resolve(__dirname, '../../../node_modules'),
        path.resolve(__dirname, '../')
      ]
    },
    devtool: 'inline-source-map',
    plugins: [new wb.optimize.DedupePlugin()]
  }
  if(moyeConf.online && moyeConf.online.basePath) conf.output.publicPath = moyeConf.online.basePath
  return conf
}
//模板预编译
gulp.task('compile-template', function(){
  for (var i = 0; i < templates.length; i++) {
    var entry = {};
    entry[templates[i]] = path.join(basePath, 'src/res/tpl/' + templates[i])
    gulp.src(entry[templates[i]])
      .pipe(webpack(webpackConf(entry, '../build/res/tpl'),null,function (err,status) {
        //console.log('webpack end')
      }))
      .pipe(gulpif(isUglify, uglify(uglifyConf)))
      .pipe(replace('!function','module.exports=(function'))
      .pipe(replace('(0)}([function','(0)})([function'))
	//lang
      .pipe(replace('src="./assets/','src="'+absPath+'/stage/index/assets/'))
      .pipe(replace('src="./../../stage/','src="'+absPath+'/stage/'))
      .pipe(replace('src="assets/','src="'+absPath+'/stage/index/assets/'))
      .pipe(gulp.dest(path.join(basePath, 'build/res/tpl/')))
  }
})

//编译任务
gulp.task('compile', function(){
  for (var i = 0; i < stages.length; i++) {
    var entry = {};
    entry['index'] = path.join(basePath, 'src/'+process.env.C_PATH+'/' + stages[i] + '/index.js')
    gulp.src(entry['index'])
      .pipe(webpack(webpackConf(entry, ''),null,function (err,status) {
        //console.log('webpack end')
      }))
	//lang
      .pipe(replace('src="./assets/','src="'+absPath+'/stage/index/assets/'))
      .pipe(replace('src="./../../stage/','src="'+absPath+'/stage/'))
      .pipe(replace('src="assets/','src="'+absPath+'/stage/index/assets/'))
      .pipe(gulp.dest(path.join(basePath, 'build/'+process.env.C_PATH+'/' + stages[i] + '/')))
      .pipe(uglify(uglifyConf))
      .pipe(rename({
        suffix: '.min'
      }))
      .pipe(gulp.dest(path.join(basePath, 'build/'+process.env.C_PATH+'/' + stages[i] + '/')))

    gulp.src(path.join(basePath, 'src/'+process.env.C_PATH+'/' + stages[i] + '/index.less'))
      .pipe(less())
	//lang
      .pipe(replace('assets/',''+absPath+'/stage/index/assets/'))
      .pipe(gulp.dest(path.join(basePath, 'build/'+process.env.C_PATH+'/') + stages[i]))
      .pipe(minifyCss({
        compatibility: '-units.ch,-units.in,-units.pc,-units.pt,-units.vh,-units.vm,-units.vmax,-units.vmin'
      }))
      .pipe(rename({
        suffix: '.min'
      }))
      .pipe(footer('/*# sourceMappingURL=index.css.map */'))
      .pipe(gulp.dest(path.join(basePath, 'build/'+process.env.C_PATH+'/') + stages[i]));
    gutil.log(gutil.colors.green('Build less: '+path.join(basePath, 'src/'+process.env.C_PATH+'/' + stages[i] + '/index.less')));
  }
})


gulp.task('copy', function(){
  gulp.src(path.join(basePath, 'src/'+process.env.C_PATH+'/**/*.html'))
    .pipe(replace('src="../../lib/','src="'+absPath+'/lib/'))
    .pipe(replace('./index.css?t=',''+absPath+'/stage/index/index.css?t='))
    .pipe(replace('./index.js?t=',''+absPath+'/stage/index/index.js?t='))
    .pipe(gulp.dest(path.join(basePath, 'build/'+process.env.C_PATH+'')));
  gutil.log(gutil.colors.green('Copy libs: build/'+process.env.C_PATH+'/**/*.html'));

  gulp.src(path.join(basePath, 'src/'+process.env.C_PATH+'/**/assets/**/*'))
    .pipe(gulp.dest(path.join(basePath, 'build/'+process.env.C_PATH+'/')));
  gutil.log(gutil.colors.green('Copy libs: build/'+process.env.C_PATH+'/**/assets'));

  gulp.src(path.join(basePath, 'src/lib/**/*'))
    .pipe(gulp.dest(path.join(basePath, 'build/lib')));
  gutil.log(gutil.colors.green('Copy libs: build/lib'));

  gulp.src(path.join(basePath, 'src/res/**/*'))
	//lang
      .pipe(replace('src="./assets/','src="'+absPath+'/stage/index/assets/'))
      .pipe(replace('src="./../../stage/','src="'+absPath+'/stage/'))
      .pipe(replace('src="assets/','src="'+absPath+'/stage/index/assets/'))
    .pipe(gulp.dest(path.join(basePath, 'build/res/')));
  gutil.log(gutil.colors.green('Copy res: build/res/values'));

  // gulp.src(path.join(basePath, 'src/res/img/**/*'))
  //   .pipe(gulp.dest(path.join(basePath, 'build/res/img/')));
  // gutil.log(gutil.colors.green('Copy res: build/res/img'));

  gulp.src(path.join(basePath, 'src/service/**/*'))
    .pipe(gulp.dest(path.join(basePath, 'build/service/')));
  gutil.log(gutil.colors.green('Copy service: build/service'));
})

gulp.task('default', function() {
  //console.log(path.join(basePath, 'src/**/*'))
  var watcherJsLess = gulp.watch(path.join(basePath, 'src/**/*.{js,less,css}'),['compile'])
  var watcherTemplate = gulp.watch(path.join(basePath, 'src/**/*.{tpl,jade,ejs,juicer}'),['compile'])
  var watcherRes = gulp.watch(path.join(basePath, 'src/**/*'),['copy'])
  watcherRes.on('change', function(event) {
    gutil.log(gutil.colors.yellow('File ' + event.path + ' was ' + event.type));
  });
});

// 启动server
gulp.task('server', function() {
  gulp.src(path.join(basePath, 'build/'))
    .pipe(webserver({
      path: '/' + pkg.name + '/' + pkg.version + '/',
      host: '0.0.0.0',
      port: port,
      livereload: true,
      directoryListing: {
        enable: true,
        path: path.join(basePath, 'build/')
      },
      middleware: function(req, res, next) {
        gutil.log('Request received: ' + req.url);
        next();
      }
    }));
  gutil.log(gutil.colors.green('http://127.0.0.1'+(parseInt(port) == 80 ? '' : ':'+port)+'/' + pkg.name + '/' + pkg.version + '/'));
  if(serverWatch){
    var watcherJsLess = gulp.watch(path.join(basePath, 'src/**/*.{js,less,css}'),['compile'])
    var watcherTemplate = gulp.watch(path.join(basePath, 'src/**/*.{tpl,jade,ejs,juicer}'),['compile'])
    var watcherRes = gulp.watch(path.join(basePath, 'src/**/*'),['copy'])
    watcherRes.on('change', function(event) {
      gutil.log(gutil.colors.yellow('File ' + event.path + ' was ' + event.type));
    });
  }
});

//service-worker编译任务
gulp.task('sw-compile', function(){
  for (var i = 0; i < stages.length; i++) {
    var entry = {};
    entry[stages[i]] = path.join(basePath, 'src/'+process.env.C_PATH+'/' + stages[i] + '/service-worker/index.js')
    if(fs.existsSync(entry[stages[i]])){
      gulp.src(entry[stages[i]])
        .pipe(webpack(webpackConf(entry, 'service-worker/'),null,function (err,status) {
          //console.log('webpack end')
        }))
        .pipe(gulp.dest(path.join(basePath, 'build/'+process.env.C_PATH+'/' + stages[i] + '/service-worker/')))
    }
  }
})

// 编译打包cyclone本地app
gulp.task('cyclone', function() {
  var cssSrc = [path.join(basePath, 'src/'+process.env.C_PATH+'/**/*.{less,css}')];
  var jsSrc = [path.join(basePath, 'src/**/*.js'), '!' + path.join(basePath, 'src/lib/**/*'), '!' + path.join(basePath, 'src/service/**/*.js')];
  // var copySrc = [
  //       path.join(basePath, 'src/*'),
  //       path.join(basePath, 'src/'+process.env.C_PATH+'/**/assets/**/*'),
  //       path.join(basePath, 'src/'+process.env.C_PATH+'/**/*.html'),
  //       path.join(basePath, 'src/res/**/*'),
  //       path.join(basePath, 'src/lib/**/*'),
  //       path.join(basePath, 'src/manifest.json'),
  //       path.join(basePath, 'src/service/**/*.js'),
  //       path.join(basePath, 'src/util/**/*'),
  //       path.join(basePath, 'src/component/**/*'),
  //       path.join(basePath, 'src/node_modules/**/*')
  //     ];
  // var copyDest = [
  //       path.join(basePath, 'buildLocal/'),
  //       path.join(basePath, 'buildLocal/'+process.env.C_PATH+'/'),
  //       path.join(basePath, 'buildLocal/'+process.env.C_PATH+'/'),
  //       path.join(basePath, 'buildLocal/res/'),
  //       path.join(basePath, 'buildLocal/lib/'),
  //       path.join(basePath, 'buildLocal/'),
  //       path.join(basePath, 'buildLocal/service/'),
  //       path.join(basePath, 'buildLocal/util/'),
  //       path.join(basePath, 'buildLocal/component/'),
  //       path.join(basePath, 'buildLocal/node_modules/')
  //     ];
  //for (var i = 0; i < copySrc.length; i++) {
  gulp.src(path.join(basePath, 'src/manifest.json'))
    .pipe(gulp.dest(path.join(basePath, 'buildLocal/')))
  gulp.src(path.join(basePath, 'src/**/*'))
    .pipe(gulp.dest(path.join(basePath, 'buildLocal/')))
    .on('end',function(){
      gulp.src(cssSrc)
        .pipe(less())
        .pipe(minifyCss())
        .pipe(gulp.dest(path.join(basePath, 'buildLocal/'+process.env.C_PATH)))
      gulp.src(jsSrc)
        .pipe(babel({
          presets: [es2015]
        }))
        .pipe(replace(/((\.tpl)|(\.jade)|(\.juicer)|(\.ejs))[\'\"]\)/g,'$1.js\'\)'))
        .pipe(gulpif(isUglify, uglify(uglifyConf)))
        .pipe(gulp.dest(path.join(basePath, 'buildLocal/')));
      for (var i = 0; i < templates.length; i++) {
        var entry = {};
        entry[templates[i]] = path.join(basePath, 'src/res/tpl/' + templates[i])
        gulp.src(entry[templates[i]])
          .pipe(webpack(webpackConf(entry, '../buildLocal/res/tpl'),null,function (err,status) {
            //console.log('webpack end')
          }))
          .pipe(uglify(uglifyConf))
          .pipe(replace('!function','module.exports=(function'))
          .pipe(replace('(0)}([function','(0)})([function'))
          .pipe(gulp.dest(path.join(basePath, 'buildLocal/res/tpl/')))
      }
    })
  //}
});