import React from 'react'
import styles from './styles.css'
import PropTypes from 'prop-types'

class AppLoading extends React.Component {
  constructor () {
    super()
    this.showed = true
    this.fading = false
    this.allowFading = false
  }

  hideAppLoading () {
    if (this.allowFading && !this.fading) {
      this.fading = true
      this.setState({})
      this.fadingTimeout = setTimeout(() => {
        this.showed = false
        this.setState({})
      }, 1000)
    } else {
      clearTimeout(this.hideTimeout)
      this.hideTimeout = setTimeout(() => {
        this.hideAppLoading()
      }, 100)
    }
  }

  componentWillReceiveProps (nextProps) {
    if (!nextProps.showed && this.showed) {
      this.hideAppLoading()
    }
  }

  componentWillMount () {
    this.showed = this.props.showed
    setTimeout(() => {
      this.allowFading = true
    }, 500)
  }

  componentWillUnmount () {
    clearTimeout(this.fadingTimeout)
    clearTimeout(this.hideTimeout)
  }

  render () {
    if (!this.showed) return null
    let containerClass = styles.container
    containerClass = this.fading ? containerClass + ' ' + styles.fading : containerClass
    return (
      <div className={containerClass} {...this.props.props}>
        {this.props.children}
      </div>
    )
  }
}

AppLoading.propTypes = {
  showed: PropTypes.bool,
  children: PropTypes.any,
  props: PropTypes.object
}

export default AppLoading
