
import { connect } from 'react-redux'
import SliderBar from 'components/SliderBar'
import SliderBarEntry from 'components/SliderBar/SliderBarEntry'
import { TableValueType } from 'components/NestedTable/data'
import { setCurBucketId, DEFAULT_REDUCER_KEY } from 'modules/metrics_data/actions'

function filterBucketsByMetricsVisiblity (buckets, curMetricIds) {
  return buckets.filter((bucket) => {
    let numValidMetricsValues = 0
    for (let serviceId of Object.keys(bucket.values)) {
      let metricValues = bucket.values[serviceId]
      for (let metricId of Object.keys(metricValues)) {
        if (curMetricIds.includes(metricId)) {
          let value = metricValues[metricId]
          if (value.type !== TableValueType.NULL) {
            numValidMetricsValues += 1
          }
        }
      }
    }
    return (numValidMetricsValues > 0)
  })
}

const mapStateToProps = (state, ownProps) => {
  let reducerKey = ownProps.reducerKey
  if (reducerKey === undefined) {
    reducerKey = DEFAULT_REDUCER_KEY
  }
  let values = []
  let sliderValue = 0
  let buckets = state.api_data.ranges
  buckets = buckets[state.user_session.startTime]
  if (buckets !== undefined) {
    buckets = buckets[state[reducerKey].curRangeEnd]
  }
  if (buckets !== undefined) {
    buckets = buckets[state[reducerKey].curBucketType]
  }
  if (buckets !== undefined) {
    buckets = buckets.buckets
  }
  if (buckets !== undefined) {
    buckets = buckets.map((id) => state.api_data.buckets[id])
    buckets = filterBucketsByMetricsVisiblity(buckets, state[reducerKey].curMetricIds)
    buckets.forEach((bucket, idx) => {
      values.push(new SliderBarEntry(bucket.id, bucket.name, bucket.shortName))
      if (bucket.id === state[reducerKey].curBucketId) {
        sliderValue = idx
      }
    })
  }

  return {
    values: values,
    disabled: state[reducerKey].loading,
    value:  sliderValue
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  let reducerKey = ownProps.reducerKey
  if (reducerKey === undefined) {
    reducerKey = DEFAULT_REDUCER_KEY
  }
  return {
    onChange: (bucketId) => {
      return dispatch(setCurBucketId(bucketId, reducerKey))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(SliderBar)
