var gulp = require('gulp');
var gutil = require('gulp-util')
var plugins = require("gulp-load-plugins")({lazy:false});
var mainBowerFiles = require('main-bower-files');
var htmlreplace = require('gulp-html-replace');

var templatesFolder = './../server/ammicosrv/ammico/templates';
var staticFolder = './../server/ammicosrv/ammico/static/ammico';
var buildFolder = './build';

var scriptsSrc = ['!./app/**/*_test.js','./app/**/*.js'];

gulp.task('templates',function(){
    //combine all template files of the app into a js file
    gulp.src(['!./app/index.html',
        './app/**/*.html'])
        .pipe(plugins.angularTemplatecache('templates.js',{standalone:true}))
        .pipe(gulp.dest(buildFolder+'/js'));
});

gulp.task('scripts', function(){
    //combine all js files of the app
    gulp.src(scriptsSrc)
        .pipe(plugins.jshint())
        .pipe(plugins.jshint.reporter('default'))
        .pipe(plugins.jshint.reporter('fail'))
        .pipe(plugins.concat('app.js'))
        .pipe(gulp.dest(buildFolder+'/js'))
        .pipe(plugins.filesize())
        .on('error', gutil.log);
});

gulp.task('css', function(){
    gulp.src('./app/**/*.css')
        .pipe(plugins.csslint({ 'box-sizing': false }))
        .pipe(plugins.csslint.reporter())
        .pipe(plugins.concat('app.css'))
        .pipe(gulp.dest(buildFolder+'/css'))
        .pipe(plugins.filesize());
});

gulp.task('vendorJS', function(){
    //concatenate vendor JS files
    return gulp.src(mainBowerFiles('**/*.js', {
            "overrides":{
                "angular": {
                    "dependencies": {
                        "jquery": "~1.8"
                    }
                }
            }
        }))
        .pipe(plugins.concat('lib.js'))
        .pipe(gulp.dest(buildFolder+'/js'))
        .pipe(plugins.filesize())
        .on('error', gutil.log);
});

gulp.task('vendorCSS', function(){
    //concatenate vendor CSS files
    gulp.src(['!./bower_components/**/*.min.css',
        './bower_components/**/*.css'])
        .pipe(plugins.concat('lib.css'))
        .pipe(gulp.dest(buildFolder+'/css'))
        .pipe(plugins.filesize());
});

gulp.task('vendorFonts', function(){
    gulp.src(['./bower_components/**/fonts/*'])
        .pipe(plugins.flatten())
        .pipe(gulp.dest(buildFolder+'/fonts'));
});

gulp.task('minimify', ['scripts', 'css', 'vendorJS', 'vendorCSS'], function(){
    gulp.src(buildFolder+'/js/lib.js')
        .pipe(plugins.uglify())
        .pipe(plugins.rename('lib.min.js'))
        .pipe(gulp.dest(buildFolder+'/js'))
        .pipe(plugins.filesize());
    gulp.src(buildFolder+'/js/app.js')
        .pipe(plugins.uglify())
        .pipe(plugins.rename('app.min.js'))
        .pipe(gulp.dest(buildFolder+'/js'))
        .pipe(plugins.filesize());
    gulp.src(buildFolder+'/css/app.css')
        .pipe(plugins.minifyCss({keepBreaks:true, processImport: false}))
        .pipe(plugins.rename('app.min.css'))
        .pipe(gulp.dest(buildFolder+'/css'))
        .pipe(plugins.filesize());
    gulp.src(buildFolder+'/css/lib.css')
        .pipe(plugins.minifyCss({keepBreaks:true, processImport: false}))
        .pipe(plugins.rename('lib.min.css'))
        .pipe(gulp.dest(buildFolder+'/css'))
        .pipe(plugins.filesize());
});

gulp.task('copy-index', function() {
    gulp.src('./app/index.html')
        .pipe(gulp.dest(buildFolder));
});

gulp.task('copy-data', function() {
    gulp.src('./data/**/*')
        .pipe(gulp.dest(buildFolder+'/data'));
});

gulp.task('copy-img', function() {
    gulp.src('./img/**/*')
        .pipe(gulp.dest(buildFolder+'/img'));
});

gulp.task('watch',function(){
    gulp.watch([
        buildFolder+'/**/*.html',
        buildFolder+'/**/*.js',
        buildFolder+'/**/*.css'
    ], function(event) {
        return gulp.src(event.path)
            .pipe(plugins.connect.reload());
    });
    gulp.watch(['./app/**/*.js','!./app/**/*test.js'],['scripts']);
    gulp.watch(['!./app/index.html','./app/**/*.html'],['templates']);
    gulp.watch('./app/**/*.css',['css']);
    gulp.watch('./app/index.html',['copy-index']);
    gulp.watch('./data/**/*',['copy-data']);
    gulp.watch('./img/**/*',['copy-img']);
});


gulp.task('connect', function() {
    plugins.connect.server({
        root: buildFolder,
    	port: 9000,
        livereload: true
    });
});

gulp.task('default',['connect','scripts','css', 'templates','copy-index','copy-data','copy-img','vendorJS','vendorCSS','vendorFonts','watch']);
gulp.task('copy-server', ['scripts','css', 'templates','copy-index','copy-data','copy-img','vendorJS','vendorCSS','vendorFonts','minimify'], function() {
    gulp.src(buildFolder+'/img/**/*')
        .pipe(gulp.dest(staticFolder+'/img'));
    gulp.src(buildFolder+'/fonts/**/*')
        .pipe(gulp.dest(staticFolder+'/fonts'));
    gulp.src(buildFolder+'/js/*.js')
        .pipe(gulp.dest(staticFolder+'/js'));
    gulp.src(buildFolder+'/css/*.css')
        .pipe(gulp.dest(staticFolder+'/css'));
    gulp.src(buildFolder+'/index.html')
        .pipe(htmlreplace({
            django: '{% load static %}',
            js:{
                src: ['lib.js', 'templates.js', 'app.js'],
                tpl: '<script src="{% static \'ammico/js/%s\' %}"></script>'
            },
            css: {
                src: ['lib.css', 'app.css'],
                tpl: '<link rel="stylesheet" type="text/css" href="{% static \'ammico/css/%s\' %}"/>'
            },
            imgLogo: {
                src: 'ammico_logo_small.png',
                tpl: '<img src="{% static \'ammico/img/%s\' %}">'
            },
            imgFooter: {
                src: 'logo_IRI_footer.png',
                tpl: '<img src="{% static \'ammico/img/%s\' %}" alt="Logo IRI" />'
            },
            idExpo: 'idExpo: "{{ context.idExpo }}",',
            ammicoUrl: 'ammicoUrl: "{{ context.ammicoUrl|safe }}",',
            searchUrl: 'searchUrl: "{{ context.searchUrl|safe }}",',
            token: '{% if context.token %} token: "{{ context.token }}", {% endif %}'
        }))
        .pipe(plugins.rename('indexAmmico.html'))
        .pipe(gulp.dest(templatesFolder));
});
