import React from 'react'
import ServiceInfo from 'routes/Services/components/ServiceInfo'
import ServiceListEntry from 'routes/Services/components/ServiceListEntry'
import ServiceGraph from 'containers/ServiceGraph'
import UrlUtils from 'utils/UrlUtils'
import { Grid } from 'react-bootstrap'
import { ORG_GRAPH_REDUCER_KEY } from '../reducers/org_graph'

export default class TeamInfo extends ServiceInfo {

  componentWillReceiveProps (nextProps) {
    if (nextProps.selectedTab === 'metrics') {
      this.setActiveTabIdx('2')
    }
  }

  setActiveTab (tabKey) {
    if (tabKey === '2') {
      UrlUtils.updateUrl(UrlUtils.getServiceMetricsUrl(this.props.serviceId, this.props.serviceType))
    } else {
      UrlUtils.updateUrl(UrlUtils.getServiceUrl(this.props.serviceId, this.props.serviceType))
    }
    super.setActiveTab(tabKey)
  }

  renderTabs () {
    const service = this.props.services[this.props.serviceId]
    return [
      ['Teams', this.renderTeams(service)],
      ['Projects', this.renderProjects(service)],
      ['Metrics', this.renderMetrics(service)]
    ]
  }

  renderTeams (service) {
    let teams = []
    service.children.forEach((teamId, idx) => {
      teams.push(<ServiceListEntry key={teamId} serviceId={teamId} services={this.props.services} hideParent />)
    })
    return (
      <div>
        <Grid style={{ marginTop: '40px' }} fluid>
          <h1 style={{ marginTop: '0px' }}>There are {teams.length} teams within this organization.</h1>
          <hr />
          {teams}
        </Grid>
      </div>
    )
  }

  renderProjects (service) {
    const services = this.props.services
    let projects = []
    let projectIds = []
    service.children.forEach((teamId, teamIdx) => {
      projectIds = projectIds.concat(services[teamId].children)
    })
    projectIds.sort((serviceIdA, serviceIdB) => {
      return services[serviceIdA].compareNameTo(services[serviceIdB])
    })
    projectIds.forEach((projectId, projectIdx) => {
      projects.push(
        <ServiceListEntry
          key={projectId}
          serviceId={projectId}
          services={this.props.services}
          hideParent
        />
      )
    })
    return (
      <div>
        <Grid style={{ marginTop: '40px' }} fluid>
          <h1 style={{ marginTop: '0px' }}>There are {projects.length} projects within this organization.</h1>
          <hr />
          {projects}
        </Grid>
      </div>
    )
  }

  renderMetrics (service) {
    return (
      <Grid style={{ marginTop: '40px' }} fluid>
        <ServiceGraph
          reducerKey={ORG_GRAPH_REDUCER_KEY}
          serviceId={this.props.serviceId}
          metricIds={this.props.metricIds}
          options={{ responsive: true }}
          showControls
          urlStr={UrlUtils.getServiceMetricsUrl(this.props.serviceId, this.props.serviceType)}
        />
      </Grid>
    )
  }
}
