import React from 'react'
import Utils from 'utils/Utils'
import { Panel } from 'react-bootstrap'
import { Link } from 'react-router'
import { ServiceType } from 'modules/api_data/types'
import './ServiceListEntry.scss'

export default class ServiceListEntry extends React.Component {

  renderTitle () {
    const service = this.props.services[this.props.serviceId]
    let rightContent = null
    if (!this.props.hideParent) {
      if (service.type === ServiceType.PROJECT) {
        rightContent = <span style={{ float: 'right' }}>{service.info.teamName}</span>
      } else if (service.type === ServiceType.TEAM) {
        rightContent = <span style={{ float: 'right' }}>{service.info.orgName}</span>
      }
    }
    return (
      <div>
        <span className='service-list-entry-header'>
          <Link to={service.url}>{service.name}</Link>
        </span>
        {rightContent}
      </div>
    )
  }

  renderContent () {
    const service = this.props.services[this.props.serviceId]
    if (service.type === ServiceType.PROJECT) {
      return (
        <div>
          Lead by {service.info.techLeadsHtml}
          <span style={{ float: 'right' }}>{service.info.lastUpdatedStr}</span>
        </div>
      )
    } else {
      let children = service.children
      let childrenType = ServiceType.PROJECT
      if (service.type === ServiceType.ORG) {
        childrenType = ServiceType.TEAM
      }

      let prefixHtml = null
      let childrenHtml = null
      if (children.length > 0) {
        if (children.length > 1) {
          prefixHtml = (
            <span>
              Contains <span className='text-count'>{children.length} </span>
              {Utils.getPluralOfServiceType(childrenType).toLowerCase()}. Including
            </span>
          )
        } else {
          prefixHtml = <span>Contains the {Utils.getPluralOfServiceType(childrenType).toLowerCase()}</span>
        }

        childrenHtml = []
        let maxIdx = children.length - 1
        children.forEach((child, idx) => {
          childrenHtml.push(
            <Link to={`/${childrenType.name.toLowerCase()}s/${child}`} key={idx}>
              {this.props.services[child].name}
            </Link>
          )
          if (idx < maxIdx) {
            childrenHtml.push(<span key={`${idx}.0`}>, </span>)
          }
        })
      } else {
        prefixHtml = (
          <i className='text-no-children'>
            Contains no {Utils.getPluralOfServiceType(childrenType).toLowerCase()}
          </i>
        )
      }

      return (
        <div className='truncated-list'>
          {prefixHtml} {childrenHtml}
        </div>
      )
    }
  }

  render () {
    return (
      <Panel header={this.renderTitle()}>
        {this.renderContent()}
      </Panel>
    )
  }
}

ServiceListEntry.propTypes = {
  services: React.PropTypes.any,
  serviceId: React.PropTypes.string,
  hideParent: React.PropTypes.bool
}
