var through = require('through2');
var path = require('path');
var gulp = require('gulp');
var cheerio = require('cheerio');
var fs = require('fs');


function html(opt) {
  var map = opt.map;
  return through.obj(function (file, enc, cb) {
    try {
      if (file.isBuffer()) {
        var htmlcode = file.contents.toString();
        var $ = cheerio.load(htmlcode, {
          decodeEntities: false
        });
        $('link[rel="stylesheet"]').each(function () {
          var link = $(this);
          var href = (link.attr('href') + '').replace(/^\//, '');
          if (map[href]) {
            link.attr('href', map[href]);
          }
        });
        $('script[src]').each(function () {
          var script = $(this);
          var src = (script.attr('src') + '').replace(/^\//, '');
          if (map[src]) {
            script.attr('src', map[src]);
          }
        });
        file.contents = new Buffer($.html());
      }
      cb(null, file);
    } catch (ex) {
      cb(ex, file);
    }
  });
}

gulp.task('html', function(){
  var map = require('./dist/map.json');
  return gulp.src('./dist/*.html').pipe(html({map: map})).pipe(gulp.dest('./dist/'));
});

gulp.task('images', function(){
  return gulp.src('./images/**/*').pipe(gulp.dest('./dist/images'));
});

gulp.task('jquery', function () {
  return gulp.src('./assets/**/*').pipe(gulp.dest('./dist/assets'));
});

gulp.task('default', function () {
  gulp.start('html','images', 'jquery');
});

