import { connect } from 'react-redux'
import NestedTable from 'components/NestedTable'
import { TableRow, TableCol, TableValue, TableSortType } from 'components/NestedTable/data'

function generateRows (state, row, service, services, sorter, values, parentRow) {
  // Add link to the service's info.
  row.url = service.url

  if (service.children.length === 0) {
    return
  }

  // Sort children by name.
  let children = service.children.map(id => services[id]).sort((serviceA, serviceB) => {
    let nameA = serviceA.name
    let nameB = serviceB.name
    if (nameA < nameB) {
      return -1
    } else if (nameA > nameB) {
      return 1
    } else {
      return 0
    }
  })

  // Now sort rows by value if we're sorting by this row.
  if (sorter !== null) {
    children = children.sort((serviceA, serviceB) => {
      let order = sorter.type
      let valueA = TableValue.getObject(values, serviceA.id, sorter.id)
      if (valueA !== undefined) {
        valueA = valueA.value
      }
      let valueB = TableValue.getObject(values, serviceB.id, sorter.id)
      if (valueB !== undefined) {
        valueB = valueB.value
      }

      if (valueA === undefined) {
        if (valueB === undefined) {
          return 0
        } else {
          return (order === TableSortType.DESCENDING) ? 1 : -1
        }
      } else {
        if (valueB === undefined) {
          return (order === TableSortType.DESCENDING) ? -1 : 1
        } else {
          if (valueA < valueB) {
            return (order === TableSortType.DESCENDING) ? 1 : -1
          } else if (valueA > valueB) {
            return (order === TableSortType.DESCENDING) ? -1 : 1
          } else {
            return 0
          }
        }
      }
    })
  }

  for (let child of children) {
    let childUrl = child.url + '/metrics'
    childUrl += `?rangeType=${state.metrics_table.curRangeType.name.toLowerCase()}`
    childUrl += `&bucketType=${state.metrics_table.curBucketType.name.toLowerCase()}`
    childUrl += `&metrics=`
    let childRow = new TableRow(child.id, child.name, row)
    childRow.cellUrl = childUrl
    generateRows(state, childRow, child, services, sorter, values, row)
  }
}

function getRows (state, values) {
  const services = state.api_data.services
  const orgIds = state.api_data.orgIds
  const sorter = null // state.metrics_table.sorter
  let rows = []
  orgIds.map((orgId) => {
    let service = services[orgId]
    // If the org has no children, then it'll have no data to render to the table.
    if (service.children.length > 0) {
      let url = service.url + '/metrics'
      url += `?rangeType=${state.metrics_table.curRangeType.name.toLowerCase()}`
      url += `&bucketType=${state.metrics_table.curBucketType.name.toLowerCase()}`
      url += `&metrics=`
      let row = new TableRow(service.id, service.name)
      row.cellUrl = url
      rows.push(row)
      generateRows(state, row, service, services, sorter, values)
    }
  })

  return rows
}

function getCols (state, ownProps) {
  let cols = []
  ownProps.metrics.forEach((id) => {
    const metric = state.api_data.metrics[id]
    cols.push(new TableCol(metric.id, metric.name, metric.description))
  })
  return cols
}

function getValues (state) {
  const curBucketId = state.metrics_table.curBucketId
  const buckets = state.api_data.buckets
  if (buckets !== undefined) {
    const bucket = buckets[curBucketId]
    if (bucket !== undefined) {
      return bucket.values
    }
  }
  return {}
}

const mapStateToProps = (state, ownProps) => {
  let values = getValues(state)
  let rows = getRows(state, values)
  let cols = getCols(state, ownProps)

  return {
    rows: rows,
    cols: cols,
    values: values,
    sorter: null,
    loading: state.metrics_table.loading,
    loadedValues: state.api_data.fetchedBuckets
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    onSortByCol: (sorter) => {
      // return dispatch(sortByMetric(sorter))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(NestedTable)
