var gulp = require('gulp');
var through = require('through2');

var tryit  = function (fn, cb) {
    var err;

    try {
        fn();
    } catch (e) {
        err = e;
    }

    if (cb) cb(err || null);
};

var minify =function(html){
    var lines = html.split(/\r?\n/);
    var newlines = [];
    lines.forEach(function(line){
        var l = line.replace(/(^\s*)|(\s*$)/g,"");
        if(l.length > 0) {
            newlines.push(l);
        }
    });
    return newlines.join('\r\n');
};

var htmlmin = function() {
    return through.obj(function(file, enc, cb) {
        if (file.isNull()) {
            cb(null, file);
            return;
        }

        function minifyHtml(buf, done) {
            var result;
            tryit(function() {
                result = new Buffer(minify(String(buf)));
            }, function(err) {
                if (err) {
                    done(err, result);
                    return;
                }
                done(null, result);
            });
        }

        var self = this;

        if (file.isStream()) {
            file.contents.pipe(function(none, buf, done) {
                minifyHtml(buf, function(err, contents) {
                    if (err) {
                        self.emit('error', err);
                        done(err);
                    } else {
                        done(null, contents);
                        self.push(file);
                    }
                    cb();
                });
            });
            return;
        }

        minifyHtml(file.contents, function(err, contents) {
            if (err) {
                self.emit('error', err);
            } else {
                file.contents = contents;
                self.push(file);
            }
            cb();
        });
    });
};



gulp.task('default', function() {

    return gulp.src('./source_templates/**/*.html')
        .pipe(htmlmin())
        .pipe(gulp.dest('templates'));
});
