import {Component} from 'substance'

const MAX_ROWS = 10

export default
class TableValueComponent extends Component {
  render($$) {
    let nrows
    const table = this.props.value
    let el = $$('div').addClass('sc-table-value')

    let tableEl = $$('table').addClass('sc-table-value')
    const columnNames = Object.keys(table.data)
    const thead = $$('thead')
    columnNames.forEach((name)=>{
      thead.append(
        $$('th').append(name)
      )
    })
    tableEl.append(thead)
    if (columnNames.length>0) {
      const tbody = $$('tbody')
      const data = table.data
      nrows = data[columnNames[0]].values.length

      for (let i = 0; i < nrows && i < MAX_ROWS; i++) {
        let tr = $$('tr')
        columnNames.forEach((name)=>{
          tr.append(
            $$('td').text(data[name].values[i])
          )
        })
        tbody.append(tr)
      }
      tableEl.append(tbody)
    }
    el.append(tableEl)

    if (nrows > MAX_ROWS) {
      el.append(
        $$('div').addClass('se-more-records').append(
          'Showing ',
          MAX_ROWS,
          ' out of ',
          nrows,
          ' rows'
        )
      )
    }

    return el
  }
}

@@ -131,22 +131,8 @@
 ) %7B%0A
-    let nrows%0A
     
@@ -161,16 +161,109 @@
 ps.value
+.data%0A    const data = table.data%0A    const rows = table.rows%0A    const cols = table.columns%0A
 %0A    let
@@ -363,16 +363,21 @@
 value')%0A
+    %0A
     cons
@@ -404,22 +404,16 @@
 ct.keys(
-table.
 data)%0A  
@@ -565,16 +565,17 @@
 (thead)%0A
+%0A
     if (
@@ -581,24 +581,12 @@
 (col
-umnNames.length%3E
+s %3E 
 0) %7B
@@ -622,88 +622,8 @@
 y')%0A
-      const data = table.data%0A      nrows = data%5BcolumnNames%5B0%5D%5D.values.length%0A%0A
     
@@ -637,28 +637,31 @@
 let 
-i
+row
  = 0; 
-i
+row
  %3C 
-n
 rows && 
 i %3C 
@@ -656,17 +656,19 @@
 rows && 
-i
+row
  %3C MAX_R
@@ -672,17 +672,19 @@
 X_ROWS; 
-i
+row
 ++) %7B%0A  
@@ -806,17 +806,12 @@
 ame%5D
-.values%5Bi
+%5Brow
 %5D)%0A 
@@ -931,17 +931,16 @@
     if (
-n
 rows %3E M
@@ -1035,17 +1035,17 @@
     
-'
+%60
 Showing 
 ',%0A 
@@ -1044,87 +1044,36 @@
 ing 
-',%0A          MAX_ROWS,%0A          ' out of ',%0A          nrows,%0A          '
+$%7BMAX_ROWS%7D of $%7Brows%7D
  rows
-'
+%60
 %0A   

Fix TableValueComponent