// @flow

import React from 'react'
import { socket, emit } from './../socket'
import { schemas } from './../../shared/schemas'

import { Host } from './Host.jsx'
import { InfoPanel } from './InfoPanel.jsx'

import {
  REQUEST_SERVICEMAP, HEARTBEAT, SERVICEMAP
} from './../../shared/events'

export class ServiceMap extends React.Component {
  state: {
    hosts: Array<Object>,
    selected?: string,
    selectedHostIndex?: number
  }
  constructor (props: Object) {
    super(props)
    this.state = {
      hosts: [],
      selectedHostIndex: 0
    }
  }
  componentWillMount () {
    emit(REQUEST_SERVICEMAP)
    socket.on(SERVICEMAP, (raw) => {
      const data = schemas[SERVICEMAP].decode(raw)
      console.log('Got servicemap:', data)
      this.setState({
        hosts: data.hosts
      })
    })
    socket.on(HEARTBEAT, (raw) => {
      const data = schemas[HEARTBEAT].decode(raw)
      const tempHosts = this.state.hosts
      this.state.hosts.map((host, index) => {
        if (host.name === data.name) {
          tempHosts[index].updatedAt = data.timestamp
          this.setState({
            hosts: tempHosts
          })
          return
        }
      })
    })
  }
  handleSelect = (key: string, index: number) => {
    this.setState({
      selected: key,
      selectedHostIndex: index
    })
  }
  render () {
    const hosts = this.state.hosts
    const gridSize = Math.floor(12 / hosts.length)
    return (
      <div className='serviceMapContainer'>
        <div className='hosts row'>
          {
            hosts.map((k, i) => {
              const host = this.state.hosts[i]
              let selected = ''
              if (this.state.selected && this.state.selected === k) {
                selected = 'selected'
              }
              return (
                <Host key={i} keyName={k} hostIndex={i} gridSize={gridSize} selected={selected} host={host} handleSelect={this.handleSelect}/>
              )
            })
          }
        </div>
        {/* // $FlowIssue */}
        <InfoPanel hostData={this.state.hosts[this.state.selectedHostIndex]} />
      </div>
    )
  }
}
