/*
 * grunt-peaches
 * https://github.com/afc163/peaches
 *
 * Copyright (c) 2013 afc163
 * 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
  
  var path = require('path');

  grunt.registerMultiTask('peaches', 'generate sprites image.', function() {
    // Force task into async mode and grab a handle to the "done" function.
    var done = this.async();

    // Merge task-specific and/or target-specific options with these defaults.
      var options = this.options({
        model: "alipay",
        servers: {
          "alipay": {
            "name":"alipay",
            "root":"./tmp",
            "username":"liuqin.sheng",
            "tmp":"./tmp",
            "baseURI":"https://i.alipayobjects.com",
            "uploadUrl":"https://ecmng.alipay.com/home/uploadFile.json"
          },
            "tfsdaily": {
              "name": "tfsdaily",
              "root": "./images",
              "tmp": "./tmp"
            }
          }
      });

      if(!options.server){
        options.server = options.servers[options.model];
      }

    var destfile, src, srcContent;

    this.files.forEach(function(fileObj) {
      if( fileObj.src.length > 1 ){
        grunt.log.warn('This plugin don\'t support multi src file mapping to one dest file');
        return;
      }

      var src = fileObj.src[0];
      var destfile = fileObj.dest;

      if (src.indexOf('-debug.css') > 0) {
          return;
      }

      if( !grunt.file.isFile(src) ){
        return;
      }

      srcContent = grunt.file.read(src);

      require('peaches')(srcContent, options, function(err, styleText) {
        if (err) {
          grunt.log.writeln('Peaches error: ' + err + '.');
          return;
        }

        // Write the destination file.
        grunt.file.write(destfile, styleText);

        // Print a success message.
        grunt.log.writeln('File "' + destfile + '" created.');
      
        // Remove temp png files
        grunt.file.glob.sync('sprite-*.png').forEach(function(f) {
          grunt.file.delete(f);
        });

        done();
      });
    });

  });

};

@@ -1249,16 +1249,37 @@
 t;%0A%0A    
+grunt.util.async.map(
 this.fil
@@ -1280,25 +1280,17 @@
 is.files
-.forEach(
+,
 function
@@ -1297,18 +1297,26 @@
 (fileObj
+,callback
 )
- 
 %7B%0A      
@@ -1606,70 +1606,8 @@
  %7D%0A%0A
-      if( !grunt.file.isFile(src) )%7B%0A        return;%0A      %7D%0A%0A
     
@@ -1792,24 +1792,49 @@
 err + '.');%0A
+          callback(err);%0A
           re
@@ -2191,34 +2191,154 @@
 %7D);%0A
-%0A        done();%0A      %7D);
+        callback(null,'done');%0A%0A      %7D);%0A    %7D,function(err,results)%7B%0A      if( !err )%7B%0A        done();%0A      %7Delse%7B%0A        done(false);%0A      %7D
 %0A   

fix bug: 当有多个文件需要处理时，只处理其中一个