/* global  a_slice */

import Promise from "./promise";
import { isArray } from "./utils";

/**
  `RSVP.denodeify` takes a "node-style" function and returns a function that
  will return an `RSVP.Promise`. You can use `denodeify` in Node.js or the
  browser when you'd prefer to use promises over using callbacks. For example,
  `denodeify` transforms the following:

  ```javascript
  var fs = require('fs');

  fs.readFile('myfile.txt', function(err, data){
    if (err) return handleError(err);
    handleData(data);
  });
  ```

  into:

  ```javascript
  var fs = require('fs');
  var readFile = RSVP.denodeify(fs.readFile);

  readFile('myfile.txt').then(handleData, handleError);
  ```

  If the node function has multiple success parameters, then `denodeify`
  just returns the first one:

  ```javascript
  var request = RSVP.denodeify(require('request'));

  request('http://example.com').then(function(res) {
    // ...
  });
  ```

  However, if you need all success parameters, setting `denodeify`'s
  second parameter to `true` causes it to return all success parameters
  as an array:

  ```javascript
  var request = RSVP.denodeify(require('request'), true);

  request('http://example.com').then(function(result) {
    // result[0] -> res
    // result[1] -> body
  });
  ```

  Or if you pass it an array with names it returns the parameters as a hash:

  ```javascript
  var request = RSVP.denodeify(require('request'), ['res', 'body']);

  request('http://example.com').then(function(result) {
    // result.res
    // result.body
  });
  ```

  Sometimes you need to retain the `this`:

  ```javascript
  var app = require('express')();
  var render = RSVP.denodeify(app.render.bind(app));
  ```

  The denodified function inherits from the original function. It works in all
  environments, except IE 10 and below. Consequently all properties of the original
  function are available to you. However, any properties you change on the
  denodeified function won't be changed on the original function. Example:

  ```javascript
  var request = RSVP.denodeify(require('request')),
      cookieJar = request.jar(); // <- Inheritance is used here

  request('http://example.com', {jar: cookieJar}).then(function(res) {
    // cookieJar.cookies holds now the cookies returned by example.com
  });
  ```

  Using `denodeify` makes it easier to compose asynchronous operations instead
  of using callbacks. For example, instead of:

  ```javascript
  var fs = require('fs');

  fs.readFile('myfile.txt', function(err, data){
    if (err) { ... } // Handle error
    fs.writeFile('myfile2.txt', data, function(err){
      if (err) { ... } // Handle error
      console.log('done')
    });
  });
  ```

  you can chain the operations together using `then` from the returned promise:

  ```javascript
  var fs = require('fs');
  var readFile = RSVP.denodeify(fs.readFile);
  var writeFile = RSVP.denodeify(fs.writeFile);

  readFile('myfile.txt').then(function(data){
    return writeFile('myfile2.txt', data);
  }).then(function(){
    console.log('done')
  }).catch(function(error){
    // Handle error
  });
  ```

  @method denodeify
  @static
  @for RSVP
  @param {Function} nodeFunc a "node-style" function that takes a callback as
  its last argument. The callback expects an error to be passed as its first
  argument (if an error occurred, otherwise null), and the value from the
  operation as its second argument ("function(err, value){ }").
  @param {Boolean|Array} argumentNames An optional paramter that if set
  to `true` causes the promise to fulfill with the callback's success arguments
  as an array. This is useful if the node function has multiple success
  paramters. If you set this paramter to an array with names, the promise will
  fulfill with a hash with these names as keys and the success parameters as
  values.
  @return {Function} a function that wraps `nodeFunc` to return an
  `RSVP.Promise`
  @static
*/
export default function denodeify(nodeFunc, argumentNames) {
  var asArray = argumentNames === true;
  var asHash = isArray(argumentNames);

  function denodeifiedFunction() {
    var nodeArgs = a_slice(arguments);

    var thisArg;

    if (!asArray && !asHash && argumentNames) {
      console.warn('Deprecation: RSVP.denodeify() doesn\'t allow setting the ' +
                   '"this" binding anymore. Use yourFunction.bind(yourThis) instead.');
      thisArg = argumentNames;
    } else {
      thisArg = this;
    }

    return Promise.all(nodeArgs).then(function(nodeArgs) {
      return new Promise(resolver);

      // sweet.js has a bug, this resolver can't defined in the constructor
      // or the a_slice macro doesn't work
      function resolver(resolve, reject) {
        function callback() {
          var args = a_slice(arguments);

          var error = args[0];
          var value = args[1];

          if (error) {
            reject(error);
          } else if (asArray) {
            resolve(args.slice(1));
          } else if (asHash) {
            var obj = {};
            var successArguments = args.slice(1);
            var name;
            var i;

            for (i = 0; i < argumentNames.length; i++) {
              name = argumentNames[i];
              obj[name] = successArguments[i];
            }

            resolve(obj);
          } else {
            resolve(value);
          }
        }

        nodeArgs.push(callback);
        nodeFunc.apply(thisArg, nodeArgs);
      }
    });
  };

  denodeifiedFunction.__proto__ = nodeFunc;

  return denodeifiedFunction;
};

@@ -4613,16 +4613,19 @@
 r can't 
+be 
 defined 

fix english