import { Component } from 'react'
import { string } from 'prop-types'

class TextWidth extends Component {
  state = {
    canvas: document.createElement('canvas')
  }

  innerRef = ref => {
    if (ref) {
      const style = window.getComputedStyle(ref)
      const font = style.font

      const baseWidth =
        10 +
        parseInt(style.paddingLeft, 10) +
        parseInt(style.paddingRight, 10) +
        parseInt(style.borderLeftWidth, 10) +
        parseInt(style.borderRightWidth, 10)

      this.setState({
        font,
        baseWidth
      })
    }
  }

  getTextWidth = (text, font) => {
    const { canvas } = this.state
    const context = canvas.getContext('2d')

    context.font = font

    const metrics = context.measureText(text)
    return Math.ceil(metrics.width)
  }

  render() {
    const { text } = this.props
    const { font, baseWidth } = this.state

    if (font === undefined || baseWidth === undefined) {
      return this.props.children({
        innerRef: this.innerRef,
        minWidth: '0px'
      })
    }

    const textWidth = this.getTextWidth(text, font)
    const elementWidth = baseWidth + textWidth

    return this.props.children({
      minWidth: `${elementWidth}px`
    })
  }
}

TextWidth.propTypes = {
  text: string.isRequired
}

TextWidth.defaultProps = {
  text: ''
}

export default TextWidth
