React = require 'react'

{div} = React.DOM


ProgressBar = React.createClass

  displayName: 'ProgressBar'

  propTypes:
    progress: React.PropTypes.oneOfType [
      React.PropTypes.string
      React.PropTypes.number
    ]
    showLabel: React.PropTypes.bool
    indeterminate: React.PropTypes.bool
    className: React.PropTypes.string

  getDefaultProps: ->
    progress: 0 # Progress percentage. Ranges from 0-100. Can also be a text label, e.g. 'Loading...'
    showLabel: true
    indeterminate: false # Ignore the progress value. Will show an indeterminate progress bar
    className: ''

  getInitialState: ->
    indPos: 0
    progWidth: 0

  componentDidMount: ->
    if @props.indeterminate
      @setState
        progWidth: @refs.progress.clientWidth
      , => 
        @startProgress()

  startProgress: ->
    @ind = setInterval =>
      {indPos, progWidth} = @state

      pos =
        if indPos <= -25 then indPos = 0
        else indPos - 1

      @setState
        indPos: pos
    , 60

    window.addEventListener('resize', @resizeWindow)

  componentWillUnmount: ->
    clearInterval(@ind)
    window.removeEventListener('resize', @resizeWindow)

  resizeWindow: ->
    clearInterval(@ind)
    @setState
      progWidth: @refs.progress.clientWidth
    , @startProgress

  render: ->
    {progress, className, showLabel, indeterminate} = @props
    {indPos, progWidth} = @state
    progressClass = "progress-bar #{className}"

    # If the progress value is a number, put a percentage on it
    if typeof progress is 'number' then progress = "#{progress}%"

    style =
      width: progress

    # Indeterminate progress bar
    if indeterminate
      bars = []
      tickWidth = 25
      numTicks = Math.floor(progWidth / tickWidth)
      style =  
        width: (numTicks + 2) * tickWidth # Add an extra 2 for the buffer when moving the bar
        transform: "translateX(#{indPos}px) translateZ(0px)"
        msTransform: "translate(#{indPos}px)"
        WebkitTransform: "translateX(#{indPos}px)"

      # Add ticks according to the width of the element
      for i in [0..numTicks]
        bars.push div {
          key: i
          className: 'ind-bar'
          style:
            width: 13
            marginRight: 12
        }


    div {
      className: progressClass
      ref: 'progress'
    },
      div {
        className: "progress #{if indeterminate then 'ind' else ''}"
        style: style
      }, bars
      div {
        className: 'progress-label'
      }, progress if showLabel


module.exports = ProgressBar