const gulp          = require('gulp');
const sass          = require('gulp-sass');
const concat        = require('gulp-concat');
const rename        = require('gulp-rename');
const uglify        = require('gulp-uglify');
const pump          = require('pump');
const jshint        = require('gulp-jshint');
const replace       = require('gulp-replace');
const connect       = require('gulp-connect');
const watch         = require('gulp-watch');
const gulpSequence  = require('gulp-sequence')
var paths = {
    srcHTML  : 'src/views/*.html',
    srcJS    : 'src/js/*.js',
    confJS   : 'src/etc/develop.js',
    dist     : 'dist/',
    distHTML : 'dist/views/'
};

gulp.task('uglify', function() {
    pump(
        [
            gulp.src([paths.srcJS, paths.confJS]),
            concat('wrapper-demo.js'),
            replace('/src/', '/dist/'),
            gulp.dest(paths.dist),
            rename('wrapper-demo.min.js'),
            uglify(),
            gulp.dest(paths.dist)
        ]
    );
});

gulp.task('html', function() {
    pump([
        gulp.src('index.html'),
        replace(/\<!\-\- BUILD \-\-\>.*\<!\-\- \/BUILD \-\-\>/sgm, '<script src="wrapper-demo.min.js"></script>'),
        gulp.dest(paths.dist)
    ]);
    pump([
        gulp.src(paths.srcHTML),
        gulp.dest(paths.distHTML)
    ]);
});

gulp.task('sass', function() {
        return gulp.src('src/sass/*.scss')
        .pipe(sass({outputStyle: 'compressed'}).on('error', sass.logError))
        .pipe(gulp.dest('css'));
});

gulp.task('pre-install', function() {
    pump([
        gulp.src('package.json'),
        replace('ssh://git@debonline.dyndns.org:', 'http://git.focasoftware.com/'),
        replace('.git', '.git#develop'),
        gulp.dest('')
    ]);
});

gulp.task('post-install', function() {
    pump([
        gulp.src('package.json'),
        replace('http://git.focasoftware.com/', 'ssh://git@debonline.dyndns.org:'),
        replace('#develop', ''),
        gulp.dest('')
    ]);
});

gulp.task('pre-commit', function() {
    return pump(
        [
            gulp.src(paths.srcJS),
            jshint('.jshintrc'),
            jshint.reporter('default'),
            jshint.reporter('fail')
        ]
    );
});

gulp.task('webserver', function() {
    pump [
        connect.server(
            {
                port: 8086,
                host: '0.0.0.0',
                livereload: true
            }
        )
    ]
});

gulp.task('watch', function() {
    gulp.watch([paths.srcJS], ['uglify']);
    gulp.watch('src/sass/*.scss', ['sass']);
});

gulp.task('reload', function() {
    gulp.src(['src/sass/*.scss', 'index.html'])
        .pipe(connect.reload());
});

gulp.task('livereload', function() {
    gulp.watch('css/*.css', ['reload']);
    gulp.watch('js/dist/*.js', ['reload']);
    gulp.watch('vistas/**/*.html', ['reload']);
    gulp.watch('index.html', ['reload']);
});

gulp.task('default', gulpSequence(['sass', 'webserver', 'livereload', 'watch']));
