/*
 * grunt-digest
 * https://github.com/hkjorgensen/grunt-digest
 *
 * Copyright (c) 2013 Henrik Kok Jorgensen
 * Licensed under the MIT license.
 */

'use strict';

module.exports = function(grunt) {

  // Please see the Grunt documentation for more information regarding task
  // creation: http://gruntjs.com/creating-tasks

  grunt.registerMultiTask('digest', 'Create digested copies of assets and add mapping to a manifest. Useful with rails applications', function() {
    var crypto = require('crypto'),
        path = require('path'),
        filemap = {},
        tally = 0,
        options;

    // Merge task-specific and/or target-specific options with these defaults.
    options = this.options({
      out: '',
      seperator: '-',
      hash: 'md5'
    });

    this.filesSrc.forEach(function(filepath) {
      var data, file, ext, base, digest, fileDigest, filepathDigest;

      file = path.basename(filepath);
      ext = path.extname(file);
      base = path.basename(filepath, ext);

      data = grunt.file.read(filepath);
      digest = crypto.createHash(options.hash).update(data).digest('hex');
      fileDigest = [base, options.seperator, digest, ext].join('');
      filepathDigest = filepath.replace(file, fileDigest);

      //Copy file
      grunt.file.copy(filepath, filepathDigest);

      //Add file to map
      filemap[file] = fileDigest;
      grunt.verbose.writeln(file.cyan + ' -> ' + fileDigest.cyan);

      //File count
      tally++;
    });

    //Write JSON Manifest
    if (options.out !== '') {
      grunt.verbose.writeln('Creating filemap: ' + options.out.cyan);
      grunt.file.write(options.out, JSON.stringify(filemap));
    }

    //Log info
    grunt.log.writeln('Digested ' + tally.toString().cyan + ' files');
  });

};

@@ -728,17 +728,17 @@
      sep
-e
+a
 rator: '
@@ -747,20 +747,25 @@
 ,%0A      
-hash
+algorithm
 : 'md5'%0A
@@ -1089,12 +1089,17 @@
 ons.
-hash
+algorithm
 ).up
@@ -1161,17 +1161,17 @@
 ions.sep
-e
+a
 rator, d

Rename options