'use strict';
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var uglify = require('gulp-uglify');
var gutil = require('gulp-util');
var runSequence = require('run-sequence');
var rename = require('gulp-rename');
var ngHtml2Js = require("gulp-ng-html2js");
var header = require('gulp-header');
var footer = require('gulp-footer');
var rollup = require('rollup').rollup;
var commonjs = require('rollup-plugin-commonjs');
var nodeResolve = require('rollup-plugin-node-resolve');
var through2 = require('through2');
var del = require('del');
var ngAnnotate = require('gulp-ng-annotate');
var cleanCss = require('gulp-clean-css');
const fs = require('fs');
const path = require('path');
const packageConfig = require('./package.json');
const camelCase = require('camel-case');

var TPL_HEADER = `var module;
try {
  module = angular.module('${packageConfig.name}.tpls', []);
} catch (e) {
  module = angular.module('${packageConfig.name}.tpls');
}
module.run(['$templateCache', function($templateCache) {
`;
var TPL_FOOTER = `
}]);`;

gulp.task('clean', function() {
  return del(['release', 'dist', 'build', 'tmp']);
});

gulp.task('js:tplBundle', function() {
  return gulp.src('./app/views/**/*.tpl.html')
    .pipe(ngHtml2Js({
        prefix: "",
        template: "$templateCache.put('views/<%= template.url %>', '<%= template.escapedContent %>');",
    }))
    .pipe(concat("templates.js"))
    .pipe(
      header(TPL_HEADER)
    )
    .pipe(
      footer(TPL_FOOTER)
    )
    .pipe(gulp.dest("./app/scripts/"));
});

gulp.task('js:compile', function() {
  return rollup({
    entry: 'app/scripts/index.js',
    plugins: [
      nodeResolve({
        jsnext: true,
        main: true
      }),
      commonjs(),
    ],
    external: ['angular', 'localforage', 'jsUtil', 'ionic',
      'ngIonic', 'uiRouter', 'kinetic', 'swipe', 'intro']
  }).then(bundle => {
    const result = bundle.generate({
      format: 'iife',
      moduleName: camelCase(packageConfig.name),
      sourceMap: true,
      globals: {
        'angular': 'angular',
        'localforage': 'localforage',
        'ionic': 'ionic',
        'jsUtil': 'jsUtil',
        'ngIonic': `'ionic'`,
        'uiRouter': `'ui.router'`,
        'kinetic': 'Kinetic',
        'swipe': 'Swipe',
        'intro': 'introJs',
      }
    });
    result.map.sourceRoot = `/${packageConfig.name}`;
    result.map.sources = result.map.sources
      .map(file => path.relative(path.join(__dirname, 'app'), file).replace(/\\/g, '/'));
    fs.mkdirSync('release');
    fs.writeFileSync('release/index.js', `${result.code}\n//# sourceMappingURL=index.js.map`);
    fs.writeFileSync('release/index.js.map', result.map.toString());
  });
});

gulp.task('js:min', function() {
  return gulp.src('./release/index.js')
    .pipe(sourcemaps.init({ loadMaps: true }))
    .pipe(ngAnnotate())
    .pipe(uglify())
    .on('error', gutil.log)
    .pipe(rename({suffix: '.min'}))
    .pipe(sourcemaps.write('.', {
      sourceRoot: `/${packageConfig.name}`,
    }))
    .pipe(gulp.dest('./release'));
});

gulp.task('css:bundle', function() {
  return gulp.src('./app/styles/index.scss')
    .pipe(sourcemaps.init())
    .pipe(sass().on('error', sass.logError))
    .pipe(concat('index.css'))
    .pipe(sourcemaps.write('.', {
      sourceRoot: `/${packageConfig.name}/styles`,
    }))
    .pipe(gulp.dest('./release'));
});

gulp.task('css:min', function() {
  return gulp.src('./release/index.css')
    .pipe(sourcemaps.init({loadMaps: true}))
    .pipe(rename('index.min.css'))
    .pipe(cleanCss())
    .pipe(sourcemaps.write('.', {
      sourceRoot: `/${packageConfig.name}/styles`,
    }))
    .pipe(gulp.dest('./release'));
});

gulp.task('resouces:copy', function() {
  return gulp.src(['./app/images/**/*'])
    .pipe(gulp.dest('./release/images'));
});

gulp.task('build', function(callback) {
  runSequence('clean', 'js:tplBundle', 'js:compile', 'js:min', 'css:bundle', 'css:min', 'resouces:copy', callback);
});
