const roundTo = require('round-to');
const pairs = require('lodash.pairs');
const sortBy = require('lodash.sortby');
const pick = require('alea-deck').pick;
const h = require('virtual-dom/h');
const isVNode = require('virtual-dom/vnode/is-vnode');
const convertHTML = require('html-to-vdom')({
  VNode: require('virtual-dom/vnode/vnode'),
  VText: require('virtual-dom/vnode/vtext')
});

const replaceEmotes = require('./replace-emotes');

function topUsers(users) {
  const rows = [
    ['#', 'nick', 'lines', 'words per line', 'last seen', 'random quote']
  ];

  sortBy(pairs(users), x => {
    return -x[1].lines;
  }).forEach((x, i) => {
    if (i > 24) {
      return;
    }

    rows.push([
      i + 1,
      x[0],
      x[1].lines,
      roundTo(x[1].avgWords, 1),
      x[1].latest.fromNow(),
      convertHTML('<span>"' + replaceEmotes(pick(x[1].quotes)) + '"</span>')
    ]);
  });

  const headings = rows[0].map(heading => {
    return h('th', heading);
  });

  // Remove the headings row.
  rows.shift();

  // Map twice! Once for each row and then again for each element.
  const body = rows.map(row => {
    return h('tr', row.map(td => {
      // Random quotes are VNodes instead of Strings in order to allow images.
      return h('td', isVNode(td) ? [td] : String(td));
    }));
  });

  return h('table', [
    h('thead', [
      h('tr', headings)
    ]),
    h('tbody', body)
  ]);
}

module.exports = topUsers;

@@ -431,16 +431,69 @@
 motes');
+%0Aconst array2vdom = require('./array-to-vdom-table');
 %0A%0Afuncti
@@ -947,513 +947,30 @@
 %0A%0A  
-const headings = rows%5B0%5D.map(heading =%3E %7B%0A    return h('th', heading);%0A  %7D);%0A%0A  // Remove the headings row.%0A  rows.shift();%0A%0A  // Map twice! Once for each row and then again for each element.%0A  const body = rows.map(row =%3E %7B%0A    return h('tr', row.map(td =%3E %7B%0A      // Random quotes are VNodes instead of Strings in order to allow images.%0A      return h('td', isVNode(td) ? %5Btd%5D : String(td));%0A    %7D));%0A  %7D);%0A%0A  return h('table', %5B%0A    h('thead', %5B%0A      h('tr', headings)%0A    %5D),%0A    h('tbody', body)%0A  %5D
+return array2vdom(rows
 );%0A%7D

use array-to-vdom-table