import './style.less'

import classnames from 'classnames'
import React from 'react'

export interface Props {
  url: string
  isPad?: boolean
  className?: string
  duration?: number
  onClick?: () => void
}

enum Status {
  PLAY,
  STOP
}

interface State {
  status: Status
}

export default class AudioBlock extends React.Component<Props, State> {
  public audio: HTMLAudioElement | null = null
  public state: State = { status: Status.STOP }
  public clickHandler = () => {
    const { status } = this.state
    const { onClick } = this.props
    const audio = this.audio as HTMLAudioElement
    if (status === Status.PLAY) {
      audio.pause()
      this.setState({ status: Status.STOP })
    } else {
      audio.currentTime = 0
      audio.play()
      this.setState({ status: Status.PLAY })
    }
    if (onClick) onClick()
  }
  public componentDidMount() {
    setTimeout(_ => {
      ;(this.audio as HTMLAudioElement).addEventListener('ended', () => {
        this.setState({ status: Status.STOP })
      })
    }, 0)
  }
  public render() {
    const { url, isPad, className, duration } = this.props
    return (
      <div
        className={classnames('ph-audio-block', className, {
          'on-play': this.state.status === Status.PLAY,
          'is-pad': isPad,
        })}
        onClick={this.clickHandler}
      >
        <div className="animation-container">
          <i className="animation-item" />
          <i className="animation-item" />
          <i className="animation-item" />
          <i className="animation-item" />
        </div>
        <span className="duration-text">{duration !== undefined && `${duration}''`}</span>
        <audio className="audio-el" ref={el => (this.audio = el)} src={url} />
      </div>
    )
  }
}
