'use strict';

var request = require('request');

module.exports = function (grunt) {
  // show elapsed time at the end
  require('time-grunt')(grunt);
  // load all grunt tasks
  require('load-grunt-tasks')(grunt);

  var reloadPort = 35729, files;

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    develop: {
      server: {
        file: 'app.js'
      }
    },
    sass: {
      dist: {
        options: {
          outputStyle: 'compressed'
        },
        files: {
          'app/css/main.css': 'app/scss/main.scss'
        }
      }
    },
    jadeUsemin: {
      main: {
        options: {},
        files: {
          src: ['views/layout.jade']
        }
      }
    },
    imagemin: {
      static: {
        options: {
          optimizationLevel: 3
        },
      },
      dynamic: {
        files: [{
          expand: true,
          cwd: 'app/img/',
          src: ['**/*.{png,jpg,gif}'],
          dest: 'app/img/'
        }]
      }
    },
    watch: {
      options: {
        nospawn: true,
        livereload: reloadPort
      },
      server: {
        files: [
          'app.js',
          'routes/*.js'
        ],
      },
      js: {
        files: ['app/js/*.js'],
        options: {
          livereload: reloadPort
        },
        tasks: ['develop']
      },
      sass: {
        files: ['app/scss/**/*.scss'],
        options: {
          livereload: reloadPort
        },
        tasks: ['sass']
      },
      jade: {
        files: ['views/*.jade'],
        options: {
          livereload: reloadPort
        }
      }
    }
  });

  grunt.config.requires('watch.server.files');
  files = grunt.config('watch.server.files');
  files = grunt.file.expand(files);

  grunt.registerTask('delayed-livereload', 'Live reload after the node server has restarted.', function () {
    var done = this.async();
    setTimeout(function () {
      request.get('http://localhost:' + reloadPort + '/changed?files=' + files.join(','),  function (err, res) {
          var reloaded = !err && res.statusCode === 200;
          if (reloaded) {
            grunt.log.ok('Delayed live reload successful.');
          } else {
            grunt.log.error('Unable to make a delayed live reload.');
          }
          done(reloaded);
        });
    }, 500);
  });

  grunt.registerTask('default', ['develop', 'watch']);
  grunt.registerTask('build', ['jadeUsemin', 'imagemin'])
};

@@ -723,14 +723,14 @@
     
-static
+images
 : %7B%0A
@@ -794,34 +794,8 @@
  %7D,%0A
-      %7D,%0A      dynamic: %7B%0A
     

fix imagemin target