var gulp = require('gulp');
var merge = require('merge2');
var concat = require('gulp-concat');
var webserver = require('gulp-webserver');
var del = require('del');
var stylus = require('gulp-stylus');

/* eslint no-path-concat: "off" */
var src = __dirname + '/src';
var dest = __dirname + '/build';
var srcDirs = [
  src + '/app.js',
  src + '/routes.js',
  src + '/controllers.js',
  src + '/services.js',
  src + '/settings.js',
  src + '/pages/**/*.js',
  src + '/services/**/*.js',
  src + '/components.js',
  src + '/components/**/*.js'
];
var libDrs = [
  './node_modules/angular/angular.min.js',
  './node_modules/angular-route/angular-route.min.js',
  './node_modules/angular-sanitize/angular-sanitize.min.js',
  './node_modules/ng-toast/dist/ngToast.min.js',
  './node_modules/jquery/dist/jquery.min.js',
  './node_modules/bootstrap-material-design/dist/js/material.min.js',
  './node_modules/bootstrap-material-design/dist/js/ripples.min.js',
  './node_modules/angular-cookies/angular-cookies.min.js',
  './node_modules/angular-md5/angular-md5.min.js'
];
var htmlDirs = [
  src + '/index.html',
  src + '/pages/**/*.html',
  src + '/components/**/*.html'
];

var cssDirs = [
  src + '/*.styl',
  src + '/pages/**/*.css',
  src + '/components/**/*.css',
  src + '/components/**/*.styl'
];

var resDirs = [
  src + '/resources/**/*.png'
]  

gulp.task('clean', function() {
  del([dest + '/**/*']);
});

gulp.task('make-app.js', function() {
  var makeAppJs = gulp.src(srcDirs);
  var makeLibJs = gulp.src(libDrs);
  var stream = merge();
  stream.add(makeLibJs);
  stream.add(makeAppJs);
  return stream
    .pipe(concat('app.js'))
    .pipe(gulp.dest(dest));
});

gulp.task('make-html', function() {
  return gulp.src(htmlDirs, {
    base: src
  })
  .pipe(gulp.dest(dest));
});

gulp.task('make-res', function() {
  return gulp.src(resDirs, {
    base: src
  })
  .pipe(gulp.dest(dest));
});

gulp.task('make-css', function() {
  var makeAppCss = gulp.src(cssDirs);
  var stream = merge();
  stream.add(makeAppCss);
  return stream
    .pipe(stylus())
    .pipe(concat('style.css'))
    .pipe(gulp.dest(dest));
});

gulp.task('default', ['clean', 'make-html', 'make-app.js', 'make-res', 'make-css'], function() {
  var proxies = {
    fallback: 'index.html',
    source: '/rest',
    target: 'http://sportalappdev.gksm.local:8110/expeditor/rest'
  };

  gulp.src(dest)
    .pipe(webserver({
      livereload: true,
      fallback: 'index.html',
      host: '0.0.0.0',
      proxies: [proxies]
    }));

  // app.js
  gulp.watch(srcDirs, ['make-app.js']);
  // html
  gulp.watch(htmlDirs, ['make-html']);
  // css
  gulp.watch(cssDirs, ['make-css']);
  // res
  gulp.watch(cssDirs, ['make-res']);``
});
