'use strict';

var gulp = require('gulp');

var $ = require('gulp-load-plugins')({
  pattern: ['gulp-*', 'main-npm-files', 'uglify-save-license', 'del']
});

module.exports = function(options) {
  gulp.task('partials', function () {
    return gulp.src([
      options.src + '/{common,components,material,general}/**/*.html',
      options.tmp + '/serve/{common,components,material,general}/**/*.html'
    ])
      .pipe($.minifyHtml({
        empty: true,
        spare: true,
        quotes: true
      }))
      .pipe($.angularTemplatecache('templateCacheHtml.js', {
        module: 'beyondApp'
      }))
      .pipe(gulp.dest(options.tmp + '/partials/'));
  });

  gulp.task('html', ['inject', 'partials'], function () {
    var partialsInjectFile = gulp.src(options.tmp + '/partials/templateCacheHtml.js', { read: false });
    var partialsInjectOptions = {
      starttag: '<!-- inject:partials -->',
      ignorePath: options.tmp + '/partials',
      addRootSlash: false
    };

    return gulp.src(options.tmp + '/serve/*.html')
      .pipe($.inject(partialsInjectFile, partialsInjectOptions))
      .pipe($.useref())
      .pipe($.if('*.js', $.ngAnnotate()))
      .pipe($.if('*.js', $.uglify({ output: {comments: $.uglifySaveLicense }}))).on('error', options.errorHandler('Uglify'))
      .pipe($.if('*.css', $.csso()))
      .pipe($.if('*.html', $.minifyHtml({
        empty: true,
        spare: true,
        quotes: true,
        conditionals: true
      })))
      .pipe(gulp.dest(options.dist + '/'))
      .pipe($.size({ title: options.dist + '/', showFiles: true }));
  });

  // Only applies for fonts from npm dependencies
  // Custom fonts are handled by the "other" task
  gulp.task('fonts', function () {
    return gulp.src($.mainNpmFiles('**/*.@(eot|svg|ttf|woff|woff2)'))
      .pipe($.flatten())
      .pipe(gulp.dest(options.dist + '/fonts/'));
  });

  gulp.task('other', function () {
    return gulp.src([
      options.src + '/**/*',
      '!' + options.src + '/**/*.{html,css,js,scss}'
    ])
      .pipe(gulp.dest(options.dist + '/'));
  });

  gulp.task('clean', function (done) {
    return $.del([options.dist + '/', options.tmp + '/'], done);
  });

  gulp.task('copy-assets', function (done) {
    return gulp.src(['client/assets/**/*'], {
            base: 'client/assets'
        }).pipe(gulp.dest(options.dist + '/../assets'));
  });

  gulp.task('build', ['copy-assets', 'styles:dist']);
};
