var gulp = require('gulp'),
  htmlmin = require("gulp-htmlmin"), //压缩html
  cleanCss = require("gulp-clean-css"), //压缩css
  imagemin = require("gulp-imagemin"), //压缩图片
  connect = require("gulp-connect"),
  cached = require("gulp-cached"),
  uglify = require('gulp-uglify'), //压缩js
  fileInclude = require('gulp-file-include'),
  autoprefixer = require('gulp-autoprefixer'), //兼容浏览器前缀
  del = require('del')
  rev = require('gulp-rev-append')//给页面的引用添加版本号，清除页面引用缓存

gulp.task('webserver', function () {
  connect.server({
    root: 'public',
    host: '127.0.0.1', //
    port: 80
  });
});
gulp.task('js', function () {
  return gulp.src('src/js/*.js')
    .pipe(uglify())
    .pipe(gulp.dest('public/js'))
});
gulp.task('css', function () {
  return gulp.src("src/css/*.css")
    .pipe(autoprefixer())
    .pipe(cleanCss({
      compatibility: 'ie8'
    }))
    .pipe(gulp.dest('public/css'))
});
gulp.task('zip', function () {
  return gulp.src("src/static/*.zip")
    .pipe(gulp.dest('public/static'))
});
gulp.task('image', function () {
  return gulp.src('src/img/*.{jpg,png,gif,svg}') //要处理的图片目录为img目录下的所有的.jpg .png .gif 格式的图片;
    .pipe(cached(imagemin()))
    .pipe(gulp.dest('public/img'))
});

gulp.task('fileinclude', function () {
  return gulp.src(['src/*/*.json', 'src/*.html'])
    .pipe(fileInclude({
      prefix: '@@',
      basepath: '@file'
    }))
    .pipe(rev())
    .pipe(htmlmin({
      collapseWhitespace: true,
      removeComments: true
    }))
    .pipe(gulp.dest('public'));
});

gulp.task('testFile', function(){
  return gulp.src(['src/test/**/*.*'])
    .pipe(gulp.dest('public/test'));
})

gulp.task('watch', function () {
  gulp.watch('src/css/*.css', ['css', 'fileinclude']);
  gulp.watch(['src/js/*.*'], ['fileinclude', 'js']);
  gulp.watch('src/img/*.*', ['image', 'fileinclude']);
  gulp.watch(['src/**.html'], ['fileinclude']);
  gulp.watch(['src/**.zip'], ['zip']);
  gulp.watch(['src/test/*'], ['testFile']);
})

gulp.task('clean', function () {
  return del('public');
});
gulp.task('default', ['clean'], function () {
  gulp.start('fileinclude', 'css', 'image', 'js', 'webserver', 'watch','zip', 'testFile');
});
gulp.task('prod', ['clean'], function () {
  gulp.start('fileinclude', 'css', 'image', 'js','zip', 'testFile');
})
