import React, { useContext } from 'react'
import PropTypes from 'prop-types'
import { ConfigureContext } from '../contex/configureContext/ConfigureContext'

interface Props {
  paths: Array<string>
}

export const FontLoader = ({ paths}: Props) => {

  const { configureState } = useContext(ConfigureContext)
  const { parameters, downloadsPath } = configureState

  const _getValueByPath = (path: any, obj: any): any => {
    let pathsArray = path.split('.')
    let propertyName = pathsArray[0]
    if (pathsArray.length === 1) return obj[propertyName]
    else {
      pathsArray.splice(0, 1)
      return _getValueByPath(pathsArray.join('.'), obj[propertyName])
    }
  }
  let fonts = paths.map((path: any) => {
    try {
      let fontParam = _getValueByPath(path, parameters)
      let font = {
        family: fontParam.filename.replace('.', '-'),
        src: `${downloadsPath}/${fontParam.filename}`
      }
      return `
          @font-face {
            font-family: "${font.family}";
            src: url("${font.src}");
          }
        `
    } catch (err) {
      return ''
    }
  })

  return (
    <style>{fonts}</style>
  )
}


FontLoader.defaultProps = {
  paths: [],
  parameters: {},
  downloadsPath: ''
}

FontLoader.propTypes = {
  paths: PropTypes.arrayOf(PropTypes.string).isRequired,
  parameters: PropTypes.object,
  downloadsPath: PropTypes.string
}

