"use strict";

(function () {

  var chalk = require('chalk');
  var gulp = require('gulp');
  var fs = require('fs');
  var childProcess = require('child_process');
  var async = require('async');
  var $ = require('gulp-load-plugins')();
  var imageminWebp = require('imagemin-webp');
  var pngquant = require('imagemin-pngquant');

  var fsp = require('../../../utils/fs.js');
  var path = require('../../../utils/path.js');

  var work = require('../../../utils/efesWorkspace.js');

  var echoLog = function echoLog(file) {
    console.log(chalk.green('发布：'), file.relative || file.path);
    return true;
  };

  var step1 = function step1(dirname, config, publishDir, options) {
    console.log(chalk.green('开始将图片转换为webp格式...'));
    // 第一步处理图片 webp
    gulp.src([path.join(dirname, config.dev_dir) + '/**/*.+(jpg|jpeg|png|gif)', "!" + path.join(dirname, config.dev_dir) + '/**/icons/*.png']).pipe($.plumber()).pipe(imageminWebp({
      quality: 50
    })()).on('error', $.util.log).on('end', function () {
      step2(dirname, config, publishDir, options);
    }).pipe($.if(options.publish && config && echoLog, gulp.dest(publishDir, {
      cwd: dirname
    })));
  };

  var step2 = function step2(dirname, config, publishDir, options) {
    console.log(chalk.green('开始压缩图片...'));
    // 第二步处理图片 压缩
    gulp.src([path.join(dirname, config.dev_dir) + '/**/*.+(jpg|jpeg|png|gif)', "!" + path.join(dirname, config.dev_dir) + '/**/icons/*.png']).pipe($.plumber()).pipe($.imagemin({
      progressive: true,
      svgoPlugins: [{
        removeViewBox: false
      }],
      use: [pngquant()]
    })).on('error', $.util.log).on('end', function () {
      step3(dirname, config, publishDir, options);
    }).pipe($.if(options.publish && config && echoLog, gulp.dest(publishDir, {
      cwd: dirname
    })));
  };

  var step3 = function step3(dirname, config, publishDir, options) {
    console.log(chalk.green('开始编译jade文件...'));
    // 第三步处理jade
    gulp.src(path.join(dirname, config.dev_dir) + '/**/*.jade').pipe($.plumber()).pipe($.jade({
      pretty: true
    })).on('error', $.util.log).on('end', function () {
      step4(dirname, config, publishDir, options);
    }).pipe($.if(options.publish && config && echoLog, gulp.dest(publishDir, {
      cwd: dirname
    })));
  };

  var step4 = function step4(dirname, config, publishDir, options) {
    console.log(chalk.green('开始复制处理其他文件...'));

    var condition = function condition(file) {
      if (!options.publish || !config || fs.statSync(file.path).isDirectory()) {
        return false;
      }
      console.log(chalk.green('发布：'), file.relative || file.path);
      return true;
    };

    // 第四步处理其他文件
    var concatfile = fsp.readJSONSync(path.join(dirname, 'concatfile.json'));
    var outPublishFile = '/**/*.+(jsx|less|sass|scss|coffee|babel|es2015|es6)';
    if (concatfile) {
      outPublishFile = '/**/*.+(js|css|jsx|less|sass|scss|coffee|babel|es2015|es6)';
    }
    gulp.src([path.join(dirname, config.dev_dir) + '/**/*', "!" + path.join(dirname, config.dev_dir) + outPublishFile, "!" + path.join(dirname, config.dev_dir) + '/**/*.+(jpg|jpeg|png|gif)', "!" + path.join(dirname, config.dev_dir) + '/**/icons/*.png', "!" + path.join(dirname, config.dev_dir) + '/**/*.jade']).on('end', function () {
      step5(options);
    }).pipe($.if(condition, gulp.dest(publishDir, {
      cwd: dirname
    })));
  };

  var step5 = function step5(options) {
    if (options.all || options.message) {
      console.log(chalk.green('开始提交git仓库...'));
      var _cmd = 'git commit -am ' + options.message;
      if (!options.all) {
        _cmd = 'git commit -m ' + options.message;
      }

      if (!options.message) {
        _cmd = 'git commit -a';
      }

      try {
        var stdout = childProcess.execSync(_cmd, {
          stdio: 'inherit'
        });
      } catch (e) {
        console.log(e);
      }
    }
  };

  module.exports = function (dirname, options) {

    var config = fsp.readJSONSync(path.join(dirname, '.efesconfig'));
    var concatfile = fsp.readJSONSync(path.join(dirname, 'concatfile.json'));

    var publishDir = config.publish_dir || './';

    publishDir = options.outpath || publishDir;

    // 第零步处理css、js
    if (concatfile.pkg) {

      /*for (let output in concatfile.pkg) {
        work.loadFile([{
          root: dirname,
          output: output,
          input: concatfile.pkg[output],
          config: config
        }], options, function(err, filedata, local) {
           console.log(chalk.green('发布：'), output);
         });
      }*/

      console.log(chalk.green('开始编译、合并js、css文件...'));
      async.forEachOfSeries(concatfile.pkg, function (input, output, cb) {
        work.loadFile([{
          root: dirname,
          output: output,
          input: input,
          config: config
        }], options, function (err, filedata, local) {
          console.log(chalk.green('发布：'), output);
          cb();
        });
      }, function (err) {
        err && config.log(err);
        step1(dirname, config, publishDir, options);
      });
    } else {
      step1(dirname, config, publishDir, options);
    }
  };
})();