var gulp = require('gulp');
// var sass = require('gulp-sass');
var less = require('gulp-less');
var del = require('del');
var concat = require('gulp-concat');
var rev = require('gulp-rev');
var revCollector = require('gulp-rev-collector');
var minifycss = require('gulp-minify-css');
var minifyhtml = require('gulp-minify-html');
var minifyjs = require('gulp-uglify');
var autoprefixer = require('gulp-autoprefixer');
// var imagemin = require('gulp-imagemin');
// var pngquant = require('imagemin-pngquant');
var templateCache = require('gulp-angular-templatecache');

// Paths to your asset files
var paths = {
    frontend: {
        scripts: [
            '../common/*.js',
            'src/js/**/*.js'
        ],
        styles: [
            'temp/css/*'
        ],
        less: [
            // '../common/*.less',
            'src/less/*.less'
        ],
        imgs: [
            'src/imgs/*'
        ],
        template: [
            'src/templates/*.html'
        ]
    }
}

var distpath = '../dist/guideview';

gulp.task('app-css', function() {
    del([distpath + '/app-*.css'], { cwd: process.cwd(), force: true });
    return gulp.src(paths.frontend.less)
        .pipe(less())
        .pipe(concat('app.css'))
        .pipe(minifycss())
        .pipe(rev())
        .pipe(gulp.dest(distpath))
        .pipe(rev.manifest('app-css-manifest.json'))
        .pipe(gulp.dest('temp/manifest'));
});

gulp.task('rev', ['app-css', 'js'], function() {
    return gulp.src(['temp/manifest/*.json', 'src/html/index.html'])
        .pipe(revCollector())
        .pipe(gulp.dest(distpath));
});

gulp.task('template', function() {
    return gulp.src(paths.frontend.template)
        .pipe(templateCache('templates.js', { module: 'templatescache', standalone: true, root: 'templates/' }))
        .pipe(gulp.dest('src/js'));
});

gulp.task('js', ['template'], function() {
    // Cleanup old assets
    del([distpath + '/app-*.js'], { cwd: process.cwd(), force: true });

    return gulp.src(paths.frontend.scripts)
        .pipe(concat('app.js'))
        .pipe(minifyjs())
        .pipe(rev())
        .pipe(gulp.dest(distpath))
        .pipe(rev.manifest('app-js-manifest.json'))
        .pipe(gulp.dest('temp/manifest'));
});

// gulp.task('imgs', function () {
//     return gulp.src(paths.frontend.imgs)
//         .pipe(imagemin({
//             progressive: true,
//             svgoPlugins: [{removeViewBox: false}],
//             use: [pngquant()]
//         }))
//         .pipe(gulp.dest('dest/assets/imgs'));
// });

gulp.task('build', ['app-css', 'template', 'js', 'rev']);

gulp.task('watch', function() {
    gulp.watch('src/less/*.less', ['app-css', 'rev']);
    gulp.watch('src/html/**/*.html', ['rev']);
    gulp.watch('src/templates/**/*.html', ['template', 'js', 'rev']);
    gulp.watch('src/js/**/*.js', ['js', 'rev']);
});

// The default task (called when you run `gulp` from cli)
gulp.task('default', ['build', 'watch']);