import { connect } from 'react-redux'
import ProjectInfo from '../components/ProjectInfo'
import { ServiceType } from 'modules/api_data/types'
import { PROJECT_INFO_REDUCER_KEY } from '../reducers/project_info'
import { PROJECT_GRAPH_REDUCER_KEY } from '../reducers/project_graph'

const mapStateToProps = (state, ownProps) => {
  let hasMetrics = false
  let hasCodeCoverage = false
  let hasTestResults = false
  let testResultsPassing = false
  let serviceHealth = 0
  let error = state.project_info.error
  const loading = state.project_info.loading
  const curBucketType = state[PROJECT_INFO_REDUCER_KEY].curBucketType
  const curRangeEnd = state[PROJECT_INFO_REDUCER_KEY].curRangeEnd

  const serviceId = ownProps.params.projectId
  const selectedTab = ownProps.params.selectedTab

  if (!loading && error === null) {
    const rangeData = state.api_data.ranges[state.user_session.startTime][curRangeEnd]
    const bucketIds = rangeData[curBucketType].buckets
    for (let bucketId of bucketIds) {
      let bucket = state.api_data.buckets[bucketId]
      const serviceValues = bucket.values[serviceId]
      if (serviceValues !== undefined) {
        hasMetrics = true
        if (!hasCodeCoverage && serviceValues.collect_coverage_results !== undefined) {
          hasCodeCoverage = serviceValues.collect_coverage_results.value
        }
        if (!hasTestResults && serviceValues.has_test_results !== undefined) {
          hasTestResults = serviceValues.has_test_results.value
        }
        if (!testResultsPassing && serviceValues.tests_passing_percent !== undefined) {
          testResultsPassing = (serviceValues.tests_passing_percent.value === 1)
          serviceHealth += serviceValues.tests_passing_percent.value
        }
      }
    }
    if (hasTestResults) {
      serviceHealth += 1
    }
    if (hasCodeCoverage) {
      serviceHealth += 1
    }
    if (hasMetrics) {
      serviceHealth += 1
    }
    serviceHealth /= 4
  }

  return {
    error,
    loading,
    curBucketType,
    curRangeEnd,
    hasMetrics,
    hasTestResults,
    hasCodeCoverage,
    testResultsPassing,
    serviceHealth,
    serviceId,
    selectedTab,
    reducerKeys: [PROJECT_INFO_REDUCER_KEY, PROJECT_GRAPH_REDUCER_KEY],
    serviceType: ServiceType.PROJECT,
    services: state.api_data.services,
    metrics: state.api_data.metrics,
    metricIds: state.api_data.metricIds
  }
}

export default connect(mapStateToProps)(ProjectInfo)
