import React, { Component } from 'react'
import moment from 'moment'
import { omit } from 'ramda'

const ONE_MINUTE = 60
const ONE_HOUR = 60 * 60
function getTimeoutMs (timestamp, format) {
  const diff = moment().diff(moment(timestamp, format), 'seconds')
  if (diff < 45) {
    return (45 - diff) * 1000
  } if (diff < 90) {
    return (90 - diff) * 1000
  } if (diff < ONE_HOUR) {
    return ONE_MINUTE * 1000
  }
  return ONE_MINUTE * 30000
}

function getElapsedTime (timestamp, format) {
  return moment(timestamp, format).fromNow()
}

class MTElapsedTime extends Component {
  constructor (props) {
    super(props)
    const { timestamp, format } = props
    this.updateElapsedTime = this.updateElapsedTime.bind(this)
    this.state = {
      elapsedTime: getElapsedTime(timestamp, format),
    }
  }

  componentDidMount () {
    this.scheduleUpdate()
  }

  componentWillUnmount () {
    clearTimeout(this.timeRef)
  }

  updateElapsedTime () {
    const { timestamp, format } = this.props
    this.setState({ elapsedTime: getElapsedTime(timestamp, format) })
    this.scheduleUpdate()
  }

  scheduleUpdate () {
    const { timestamp, format } = this.props
    const timeoutMs = getTimeoutMs(timestamp, format)
    this.timeRef = setTimeout(this.updateElapsedTime, timeoutMs)
  }

  render () {
    const otherProps = omit([ 'timestamp', 'format' ], this.props)
    const { elapsedTime } = this.state
    return <span { ...otherProps }>{ elapsedTime }</span>
  }
}

export default MTElapsedTime
