var gulp = require('gulp'),
    coffee = require('gulp-coffee'),
    less = require('gulp-less'),
    sourcemaps = require('gulp-sourcemaps'),
    concat = require('gulp-concat'),
    Q = require('q'),
    http = require('http'),
    express = require('express');


gulp.task('serve', function() {
  var host = '0.0.0.0';
  var port = +(process.env.PORT || 5000);
  var app = express().use('/', express.static(__dirname + '/build'));
  http.createServer(app).listen(port, host, function() {
    console.log('devel server listening on ' + host + ':' + port);
  })

  return Q.defer().promise;
});


gulp.task('ciucas', function() {
  require('coffee-script/register');
  return require('./src/data.coffee').build('ciucas');
});


gulp.task('data', function() {
  require('coffee-script/register');
  return require('./src/data.coffee').buildAll();
});


gulp.task('html', function() {
  require('coffee-script/register');
  return require('./src/data.coffee').html();
});


gulp.task('libs', function() {
  var done = Q.defer();
  var request = require('request');
  var fs = require('fs');
  var cdnjs = 'http://cdnjs.cloudflare.com/ajax/libs/';
  request(cdnjs + 'd3/3.5.3/d3.min.js', function(err, res, body) {
    fs.writeFileSync('build/d3.min.js', body);
    request(cdnjs + 'topojson/1.6.9/topojson.min.js', function(err, res, body) {
      fs.writeFileSync('build/topojson.min.js', body);
      request(cdnjs + 'twitter-bootstrap/3.3.2/css/bootstrap.min.css', function(err, res, body) {
        fs.writeFileSync('build/bootstrap.min.css', body);
        done.resolve();
      });
    });
  });
  return done.promise;
});


gulp.task('ui', function() {
  gulp.src('src/ui/**/*.coffee')
    .pipe(sourcemaps.init())
    .pipe(coffee())
    .pipe(concat('ui.js'))
    .pipe(sourcemaps.write('./'))
    .pipe(gulp.dest('./build'));

  gulp.src('src/ui/region.less')
    .pipe(less())
    .pipe(gulp.dest('./build'))
});


gulp.task('auto', function() {
  gulp.start('ui');
  gulp.watch('src/ui/**/*', ['ui']);
});


gulp.task('devel', ['auto', 'serve']);
gulp.task('default', ['data', 'ui', 'html', 'libs']);

@@ -1634,18 +1634,18 @@
 p.task('
-ui
+js
 ', funct
@@ -1650,24 +1650,31 @@
 ction() %7B%0A  
+return 
 gulp.src('sr
@@ -1835,18 +1835,60 @@
 ild'));%0A
-%0A 
+%7D);%0A%0A%0Agulp.task('css', function() %7B%0A  return
  gulp.sr
@@ -1963,24 +1963,96 @@
 ld'))%0A%7D);%0A%0A%0A
+gulp.task('ui', %5B'js', 'css'%5D, function() %7B%0A  gulp.start('html');%0A%7D);%0A%0A%0A
 gulp.task('a
@@ -2127,16 +2127,56 @@
 'ui'%5D);%0A
+  gulp.watch('templates/**/*', %5B'ui'%5D);%0A
 %7D);%0A%0A%0Agu
@@ -2251,16 +2251,8 @@
 ui',
- 'html',
  'li

build html as part of the ui