import React from 'react'
import { object, string, any } from 'prop-types'
import { connect } from 'react-redux'
import { statePath } from '../helpers'

class CellRenderer extends React.Component {
  render() {
    const { value, col, config, id } = this.props
    const Renderer = config.renderers[col]
    const colConfig = config.byId[col]
    const { router } = this.context

    return (
      <Renderer
        className={col}
        id={id}
        value={value}
        config={colConfig}
        col={col}
        router={router}
      />
    )
  }
}

CellRenderer.contextTypes = {
  router: object
}

CellRenderer.propTypes = {
  col: string.isRequired,
  config: object.isRequired,
  id: string.isRequired,
  router: object,
  value: any
}

const mapState = (state, { id, col, config }) => {
  const p = statePath(state, config.path)
  return {
    value: p.byId[id][col]
  }
}

export default connect(mapState)(CellRenderer)
