/**
 *
 * @jsx React.DOM
 */
var R = require('ramda');

function getPath(path) {
  if (typeof path === 'string') {
    return [path];
  }
  return path;
}

function autoLabel(path) {
  try {
    var attr = path;
    if (typeof path !== 'string'){
      attr = path[path.length-1];
    }
    attr = attr.replace(/[\_]/g, ' ');
    attr = attr[0].toUpperCase() + attr.slice(1);
    return attr;
  }
  catch (e) {
    return '';
  }
}

function isNumber(val) {
  return !isNaN(parseFloat(val)) && isFinite(val);
}

function iconOrText(text, icon) {
  return icon ? <img className="rf-icon" src={icon} title={text} alt={text} /> : text;
}

function newTableRow(columns) {
  var emptyRow = columns.reduce(function(acc, column) {
    if (column.get('type') == 'ActionsColumn') {
      return acc;
    }
    var key = column.get('attr');
    return acc.set(key, I.Map({value: ''}));
//    console.log(field.toJS(), key);
  }, I.Map({'_editable': true}));

  emptyRow = emptyRow.set('id', I.Map({value: ''}));
  emptyRow = emptyRow.set('actions', I.fromJS([
    {'attr': 'instant-remove',
     'label': 'Remove',
     'action': function(path, globalData) {
       var tableValuePath = path.slice(0, path.length-1);
       var row = globalData.getIn(path);
       var value = globalData.getIn(tableValuePath);
       var withoutRow = value.filter(function(r) { return r !== row; });
       FormActions.update(tableValuePath, withoutRow, true);
     }
    }
  ]));

  console.log('emptyRow', emptyRow.toJS());
  return emptyRow;
}


function get(prop, obj) {
  if(arguments.length === 1) {
      return function (obj) { return obj.get(prop); };
  }
  return obj.get(prop);
}

function getOrNull(prop, obj) {
  if(arguments.length === 1) {
      return function (obj) { return obj && obj.get ? obj.get(prop) : null; };
  }
  return obj && obj.get ? obj.get(prop) : null;
}

function propEq(prop, equalTo, obj) {
  if(arguments.length === 2) {
    return function(obj) { return obj.get(prop) === equalTo; };
  }
  return obj.get(prop) === equalTo;
}

function compareFun(fieldType) {
  console.log('comparator', fieldType);
  var fun = function (a, b) {
      var aStr = a || '';
      var bStr = b || '';
      return aStr.toLowerCase() < bStr.toLowerCase(); };
  var numCompare = ['IntField', 'NumberField'];
  if (R.contains(fieldType)(numCompare)) {
    return function (a, b) { return a < b; };
  }

  if (fieldType === 'ObjectSelectorField') {
    return function (a, b) { var av = getOrNull('display', a);
                             var bv = getOrNull('display', b);
    return fun(av, bv);};
  }

  return fun;
}

function forEachField(state, cb) {
  function fef(cb, path, state) {
    state.forEach(function(value, key) {
      if(I.Map.isMap(value) && value.has('value')){
        cb(value, path.concat([key]));
      }

      if (value.has('subfields')) {
        //object-selector  
        fef(cb, path.concat([key]), value.get('subfields'));
      }
      if (value.get('columns') && value.get('value')) {
        //objects-table
        columns = value.get('columns');
        rows = value.get('value');
        rows.forEach(function(row, index){
          if (!row.get('_editable')) {
            return;
          }

          columns.forEach(function(column){
            var attr = column.get('attr');
            var rField = column.merge(row.get(attr));
            cb(rField, path.concat([key, 'value', index.toString(), attr]));
          });
        });
      }
    });
  }
  fef(cb, [], state);
}

function recursiveFind(predicate, objectMap) {
  return objectMap.find(function(value, key, iter) {
    if(predicate(value, key, iter)) {
      return true;
    }
    if (I.Iterable.isIterable(value)) {
      return recursiveFind(predicate, value);
    }
    return false;
  });

}

module.exports = {
  getPath: getPath,
  autoLabel: autoLabel,
  isNumber: isNumber,
  iconOrText: iconOrText,
  newTableRow: newTableRow,
  get: get,
  propEq: propEq,
  compareFun: compareFun,
  forEachField: forEachField,
  recursiveFind: recursiveFind
};
