import React from 'react'
import TabsView from 'views/TabsView'
import { fetchServiceInfoRoute } from 'routes/Services/actions'
import { BucketType, ServiceType, RangeType } from 'modules/api_data/types'
import ServiceCrumb from 'routes/Services/components/ServiceCrumb'
import Utils from 'utils/Utils'
import './ServiceInfo.scss'
import { DEFAULT_REDUCER_KEY } from 'modules/metrics_data/actions'

export default class ServiceInfo extends TabsView {

  componentDidMount () {
    let reducerKeys = this.props.reducerKeys
    if (reducerKeys === undefined) {
      reducerKeys = [DEFAULT_REDUCER_KEY]
    }
    let bucketType
    let rangeType
    let metricIds
    const selectedTab = this.props.selectedTab
    if (selectedTab === 'metrics') {
      const urlQuery = this.props.location.query
      if (urlQuery !== undefined) {
        bucketType = urlQuery.bucketType
        if (bucketType !== undefined) {
          bucketType = BucketType.enumValueOf(bucketType.toUpperCase())
        }
        rangeType = urlQuery.rangeType
        if (rangeType !== undefined) {
          rangeType = RangeType.enumValueOf(rangeType.toUpperCase())
        }
        metricIds = urlQuery.metrics
        if (metricIds !== undefined) {
          metricIds = metricIds.split(',')
        }
      }
    }
    this.props.dispatch(
      fetchServiceInfoRoute(this.props.serviceId, this.props.serviceType, rangeType, bucketType, metricIds, reducerKeys)
    )
  }

  documentTitle () {
    if (this.props.error !== null || this.props.loading) {
      return Utils.getPluralOfServiceType(this.props.serviceType)
    }
    const service = this.props.services[this.props.serviceId]
    return service.name
  }

  renderHeader () {
    const service = this.props.services[this.props.serviceId]
    let subtitle = null
    if (this.props.serviceType === ServiceType.PROJECT) {
      subtitle = (
        <h3 style={{ marginTop: '-10px', marginBottom: '20px' }}>
          <small>Lead by {service.info.techLeadsHtml}</small>
        </h3>
      )
    }
    return (
      <div>
        <ServiceCrumb serviceId={this.props.serviceId} services={this.props.services} />
        <h1 className='service-info-header'>{service.name}</h1>
        {subtitle}
      </div>
    )
  }
}
