// @flow

const React = require('react')

import { Table } from 'react-bootstrap'
import { emit, socket } from './../socket'

import { PROCESSLIST, PROCESSLIST_DATA } from './../../shared/events'
import { schemas } from './../../shared/schemas'

export class ProcessList extends React.Component {
  state: {
    updated: number,
    processlist: [
      {
        Command: string,
        Info: string,
        State: string,
        Time: string
      }
    ]
  }
  constructor (props: Object) {
    super(props)
    this.state = {
      updated: Date.now(),
      processlist: [
        {
          Command: 'One',
          Info: 'Two',
          State: 'Three',
          Time: 'Four'
        }
      ]
    }
  }
  componentWillMount () {
    emit(PROCESSLIST, { running: true, host: '*' })
    socket.on(PROCESSLIST_DATA, (raw) => {
      const data = schemas[PROCESSLIST_DATA].decode(raw)
      console.log('Got data:', data)
      this.setState({
        updated: Date.now(),
        processlist: data
      })
    })
  }
  componentWillUnmount () {
    emit(PROCESSLIST, { running: false, host: '*' })
    socket.removeListener('processlist')
  }
  render () {
    return (
      <div style={{ width: '50%', margin: '0 auto', textAlign: 'center' }}>
        <div>Last updated: { this.state.updated }</div>
        <Table striped bordered condensed hover>
          <thead>
            <tr>
              <th>Command</th>
              <th>Info</th>
              <th>State</th>
              <th>Time</th>
            </tr>
          </thead>
          <tbody>
            { this.state.processlist.map((p, i) => {
              // if (p['Info'] === 'show full processlist') {
              //   return
              // }
              return (
                <tr key={ i }>
                  <td>{ p['Command'] }</td>
                  <td>{ p['Info'] }</td>
                  <td>{ p['State'] }</td>
                  <td>{ p['Time'] }</td>
                </tr>
              )
            }) }
          </tbody>
        </Table>
      </div>
    )
  }
}
