import computed from 'ember-computed';
import collapseKeys from './collapse-keys';
import flattenKeys from './flatten-keys';

function parseComputedArgs(args) {
  return {
    keys: args.slice(0, -1),
    callback: args[args.length - 1]
  };
}

function buildCallback(keys, incomingCallback, getValue) {
  let collapsedKeys = collapseKeys(keys);

  let newCallback;
  if (typeof incomingCallback === 'function') {
    newCallback = function() {
      let values = collapsedKeys.map(key => getValue(this, key));
      return incomingCallback.apply(this, values);
    };
  } else {
    newCallback = {};
    if (incomingCallback.get) {
      newCallback.get = function() {
        let values = collapsedKeys.map(key => getValue(this, key));
        return incomingCallback.get.apply(this, values);
      };
    }
    if (incomingCallback.set) {
      newCallback.set = incomingCallback.set;
    }
  }

  return newCallback;
}

export default function(args, getValue) {
  let { keys, callback: incomingCallback } = parseComputedArgs(args);

  let newCallback = buildCallback(keys, incomingCallback, getValue);

  return computed(...flattenKeys(keys), newCallback);
}

@@ -238,16 +238,121 @@
   %7D;%0A%7D%0A%0A
+function mapKeysToValues(keys, getValue, context) %7B%0A  return keys.map(key =%3E getValue(context, key));%0A%7D%0A%0A
 function
@@ -398,24 +398,24 @@
 getValue) %7B%0A
-
   let collap
@@ -554,32 +554,48 @@
    let values = 
+mapKeysToValues(
 collapsedKeys.ma
@@ -587,35 +587,25 @@
 ollapsedKeys
-.map(key =%3E
+,
  getValue(th
@@ -597,35 +597,30 @@
 ys, getValue
-(
+, 
 this
-, key)
 );%0A      ret
@@ -787,24 +787,40 @@
 et values = 
+mapKeysToValues(
 collapsedKey
@@ -820,27 +820,17 @@
 psedKeys
-.map(key =%3E
+,
  getValu
@@ -834,19 +834,14 @@
 alue
-(
+, 
 this
-, key)
 );%0A 

refactor use of getValue