import React from 'react'
import PropTypes from 'prop-types'

/**
 *
 * @param {Object} MetaOptions anything that can be used in meta element or title, the key is used as meta name and the value as meta content property
 */
export default function(MetaOptions) {
  return function(WrappedComponent) {
    class MetaHelper extends React.Component {
      static contextTypes = {
        isAlreadyLoggedIn: PropTypes.func,
      }
      componentDidMount() {
        if (
          typeof MetaOptions == 'object' &&
          Object.keys(MetaOptions).length > 0
        ) {
          this.updateMeta(MetaOptions)
        }
      }
      updateMeta(options) {
        const metas = Object.keys(options).map(name => {
          if (name === 'title') {
            let title = document.createElement('title')
            title.innerText = options[name]
            title.className = 'meta-helper'
            return title
          }
          let meta = document.createElement('meta')
          meta.name = name
          meta.content = options[name]
          meta.className = 'meta-helper'
          return meta
        })

        let previousMetas = Array.from(
          document.head.querySelectorAll('.meta-helper'),
        )
        previousMetas.forEach(meta => meta.remove())
        metas.forEach(meta => {
          document.head.appendChild(meta)
        })
      }
      render() {
        const props = this.props
        return <WrappedComponent {...props} updateMeta={this.updateMeta} />
      }
    }
    return MetaHelper
  }
}
