import { connect } from 'react-redux'
import { ToggleTable, ToggleEntry } from 'components/ToggleTable'
import { showMetricId, hideMetricId, DEFAULT_REDUCER_KEY } from 'modules/metrics_data/actions'

const mapStateToProps = (state, ownProps) => {
  let reducerKey = ownProps.reducerKey
  if (reducerKey === undefined) {
    reducerKey = DEFAULT_REDUCER_KEY
  }
  let entries = []
  const metrics = state.api_data.metrics
  let metricIds = ownProps.metricIds
  if (metricIds === undefined) {
    metricIds = state.api_data.metricIds
  }
  for (const id of metricIds) {
    const entry = new ToggleEntry(id, metrics[id].name)
    entry.hidden = !(state[reducerKey].curMetricIds.indexOf(id) >= 0)
    entries.push(entry)
  }

  return {
    metrics: entries,
    hidden: ownProps.hidden
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  let reducerKey = ownProps.reducerKey
  if (reducerKey === undefined) {
    reducerKey = DEFAULT_REDUCER_KEY
  }
  return {
    onSelect: (metric) => {
      if (metric.hidden) {
        return dispatch(showMetricId(metric.id, reducerKey, ownProps.urlStr))
      } else {
        return dispatch(hideMetricId(metric.id, reducerKey, ownProps.urlStr))
      }
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(ToggleTable)
