// Generated by CoffeeScript 1.3.3

define(['underscore'], function(_) {
  var renderTable, sortedGroupBy;
  sortedGroupBy = function(list, groupBy, sortBy) {
    var groupByIter, groups, sortByIter;
    if (_.isArray(groupBy)) {
      groupByIter = function(obj) {
        return _.map(groupBy, function(key, value) {
          return obj[key];
        });
      };
    } else {
      groupByIter = groupBy;
    }
    if (_.isArray(sortBy)) {
      sortByIter = function(obj) {
        return _.map(sortBy, function(key, value) {
          return obj[key];
        });
      };
    } else {
      sortByIter = sortBy;
    }
    groups = _.groupBy(list, groupByIter);
    if (sortByIter) {
      _.each(groups, function(value, key, list) {
        return list[key] = _.sortBy(value, sortByIter);
      });
    }
    return groups;
  };
  renderTable = function(groups, keys, sep) {
    var html;
    html = [];
    sep = sep || ',';
    _.each(groups, function(list, groupKey) {
      var group, header, label, table, tbody;
      group = $('<div>').addClass('group');
      label = $('<span>').addClass('group-label');
      table = $('<table>').addClass('group-table');
      header = $('<tr>');
      tbody = $('<tbody>');
      if (_.isString(groupKey)) {
        _.each(groupKey.split(sep), function(tok) {
          return label.append('<span class=group-key>' + $.trim(tok) + '</span>');
        });
      } else {
        label.append('<span class=group-key>' + groupKey + '</span>');
      }
      _.each(list, function(obj, i) {
        var tr;
        tr = $('<tr>');
        _.each(obj, function(value, key) {
          if (keys.indexOf(key) >= 0) {
            return i === 0;
          } else {
            if (i === 0) {
              header.append('<th>' + key + '</th>');
            }
            return tr.append('<td>' + value + '</td>');
          }
        });
        return tbody.append(tr);
      });
      $('<thead>').appendTo(table).append(header);
      table.append(tbody);
      group.append(label, table);
      return html.push(group);
    });
    return html;
  };
  return {
    sortedGroupBy: sortedGroupBy,
    renderTable: renderTable
  };
});
