React = require 'react'
createClass = require 'create-react-class'
ReactDOM = require 'react-dom'
Spin = require 'spin'
clone = require 'lodash/clone'
defaults = require 'lodash/defaults'


Spinner = createClass

  defaults:
    lines: 10 # The number of lines to draw
    length: 5 # The length of each line
    width: 2 # The line thickness
    radius: 4 # The radius of the inner circle
    corners: 1 # Corner roundness (0..1)
    rotate: 0 # The rotation offset
    direction: 1 # 1: clockwise, -1: counterclockwise
    color: '#000000' # #rgb or #rrggbb or array of colors
    speed: 1 # Rounds per second
    trail: 60 # Afterglow percentage
    shadow: false # Whether to render a shadow
    hwaccel: false # Whether to use hardware acceleration
    className: 'spinner' # The CSS class to assign to the spinner
    zIndex: 15 # The z-index (defaults to 2000000000)


  displayName: 'spinner'


  render: ->
    {div, table, tbody, tr, td} = require 'react-dom-factories'

    {textPosition, spinnerText} = @props
   
    content = div {
      ref: 'spinner'
      className: 'spinner-wrapper'
    }    

    # if spinner text then display text to the right
    if spinnerText
      content = table {}, 
        tbody {},
          tr {}, [
            td {
              key: 'table-spinner'
              ref: 'spinner'
              className: 'spinner-wrapper right'
            }
            td {
              key: 'table-text'
            }, spinnerText
          ]
      
    content


  componentDidMount: ->
    # Extend the defaults into the props
    props = clone @props
    defaults(props, @defaults)

    # Create a new spinner instance and start the spinning
    @spinner = new Spin(props).spin()
    ReactDOM.findDOMNode(@refs.spinner).appendChild(@spinner.el)


  stop: ->
    @spinner.stop()


module.exports = Spinner


