import React from 'react'
import ServiceInfo from 'routes/Services/components/ServiceInfo'
import HealthBar from 'components/HealthBar'
import ServiceGraph from 'containers/ServiceGraph'
import {
  Glyphicon,
  Panel,
  Grid,
  Row,
  Col
} from 'react-bootstrap'
import { PROJECT_INFO_REDUCER_KEY } from '../reducers/project_info'
import { PROJECT_GRAPH_REDUCER_KEY } from '../reducers/project_graph'
import UrlUtils from 'utils/UrlUtils'

export default class ProjectInfo extends ServiceInfo {

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

  setActiveTab (tabKey) {
    if (tabKey === '1') {
      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 [
      ['Summary', this.renderSummary(service)],
      ['Metrics', this.renderMetrics(service)]
    ]
  }

  renderSummary (service) {
    let serviceInfoText = service.info.about
    if (serviceInfoText === undefined) {
      serviceInfoText = (
        <i className='text-no-content'>
          This project doesn't have an about section.
        </i>
      )
    }
    return (
      <div>
        <Grid style={{ marginTop: '40px' }} fluid>
          <Row>
            <Col sm={6}>
              {this.renderCurrentHealth(service)}
            </Col>
            <Col sm={6}>
              {this.renderHealthGraph(service)}
            </Col>
          </Row>
          <Panel header={'About this Project'}>
            <p>{serviceInfoText}</p>
            {this.renderBlueprintLocation(service)}
            {this.renderDeveloperList(service)}
          </Panel>
          {this.renderGitHubRepos(service)}
          {this.renderJenkinsJobs(service)}
          {this.renderJiraProjects(service)}
        </Grid>
      </div>
    )
  }

  renderBlueprintLocation (service) {
    let blueprintUrl = service.info.blueprintUrl
    if (blueprintUrl === undefined) {
      return null
    }
    return (
      <div>
        <hr />
        <h4>Blueprint File:</h4>
        <ul>
          <li><a href={blueprintUrl} target='_blank'>{service.info.blueprintName}</a></li>
        </ul>
      </div>
    )
  }

  renderDeveloperList (service) {
    let developers = []
    service.info.techLeads.forEach((techLead, idx) => {
      developers.push(
        <li key={`t.${idx}`}>
          <a href={`https://git-aws.internal.justin.tv/${techLead}`} target='_blank'>
            {techLead}
          </a> <i> - Lead</i>
        </li>
      )
    })
    service.info.developers.forEach((developer, idx) => {
      developers.push(
        <li key={`d.${idx}`}>
          <a href={`https://git-aws.internal.justin.tv/${developer}`} target='_blank'>
            {developer}
          </a>
        </li>
      )
    })
    if (developers.length <= 0) {
      return null
    }
    return (
      <div>
        <hr />
        <h4>Developers:</h4>
        <ul>
          {developers}
        </ul>
      </div>
    )
  }

  renderGitHubRepos (service) {
    let content = null
    if (service.info.repositories === undefined) {
      content = (
        <i className='text-no-content'>
          This project doesn't have any repositories associated with it.
          You can add them to this project's <a href='http://link.twitch.tv/rps-enroll' target='_blank'>
          blueprint file</a>.
        </i>
      )
    } else {
      let repoEntries = []
      service.info.repositories.forEach((repo, idx) => {
        const name = repo.github_repository.name
        const url = `https://git-aws.internal.justin.tv/${name}`
        repoEntries.push(<li key={idx}><a href={url}>{name}</a></li>)
      })
      content = <ul>{repoEntries}</ul>
    }

    return (
      <Panel header={'Associated GitHub Repositories'}>
        {content}
      </Panel>
    )
  }

  renderJenkinsJobs (service) {
    let content = null
    if (service.info.buildServices === undefined) {
      content = (
        <i className='text-no-content'>
          This project doesn't have any Jenkins Jobs associated with it.
          You can add them to this project's <a href='http://link.twitch.tv/rps-enroll' target='_blank'>
          blueprint file</a>.
        </i>
      )
    } else {
      let entries = []
      service.info.buildServices.forEach((job, idx) => {
        const name = job.jenkins_job.name
        let url = `https://jenkins.internal.justin.tv/job/${name}`
        entries.push(<li key={idx}><a href={url}>{name}</a></li>)
      })
      content = <ul>{entries}</ul>
    }

    return (
      <Panel header={'Associated Jenkins Jobs'}>
        {content}
      </Panel>
    )
  }

  renderJiraProjects (service) {
    let content = null
    if (service.info.issueTrackers === undefined) {
      content = (
        <i className='text-no-content'>
          This project doesn't have any Jira Projects associated with it.
          You can add them to this project's <a href='http://link.twitch.tv/rps-enroll' target='_blank'>
          blueprint file</a>.
        </i>
      )
    } else {
      let entries = []
      service.info.issueTrackers.forEach((issueTracker, idx) => {
        const jiraProject = issueTracker.jira_project.project
        const jiraComponent = issueTracker.jira_project.component
        let name = `${jiraProject}`
        let url = `https://jira.twitch.com/issues/?jql=project%20%3D%20${jiraProject}`
        if (jiraComponent !== undefined) {
          name += `/${jiraComponent}`
          url += `%20AND%20component%20%3D%20${jiraComponent}%20ORDER%20BY%20created%20DESC`
        }
        entries.push(<li key={idx}><a href={url}>{name}</a></li>)
      })
      content = <ul>{entries}</ul>
    }

    return (
      <Panel header={'Associated Jira Projects'}>
        {content}
      </Panel>
    )
  }

  renderCurrentHealth (service) {
    const ok = <Glyphicon glyph='ok' className='text-green' />
    const bad = <Glyphicon glyph='remove' className='text-red' />
    return (
      // Determine if we have the data that we need.
      <Panel header={'Current Project Health'}>
        <HealthBar health={this.props.serviceHealth} />
        <div>{ (this.props.hasCodeCoverage) ? ok : bad } Reporting Code Coverage</div>
        <div>{ (this.props.hasTestResults) ? ok : bad } Reporting Test Results</div>
        <div>{ (this.props.testResultsPassing) ? ok : bad } Tests are Passing</div>
        <div>{ (this.props.hasMetrics) ? ok : bad } Collecting Metrics</div>
        <div style={{ marginBottom: '118px' }} />
      </Panel>
    )
  }

  renderHealthGraph (service) {
    return (
      <Panel header={'Metrics for the Last 7 Days'}>
        <a onClick={() => this.setActiveTab('1')}>
          <ServiceGraph
            reducerKey={PROJECT_INFO_REDUCER_KEY}
            serviceId={this.props.serviceId}
            metricIds={this.props.metricIds}
            options={{ responsive: true }}
          />
        </a>
      </Panel>
    )
  }

  renderMetrics (service) {
    return (
      <Grid style={{ marginTop: '40px' }} fluid>
        <ServiceGraph
          reducerKey={PROJECT_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>
    )
  }
}
