import React from 'react'
import { isNumber } from 'lodash'

const alignments = {
  center: 'center',
  left: 'flex-start',
  right: 'flex-end'
}

type aligment = {
  horizontal: keyof typeof alignments,
  vertical: keyof typeof alignments
}


interface Props {
  format?: any
  lineHeight: number
  maxChar?: number
  style?: number
  text: string
  unit: string
}
export const FormattedText = ({ text, format, maxChar, lineHeight, style, unit }: Props) => {

  const trimText = (text: any, maxChar: any) => {
    const isValid = maxChar && isNumber(maxChar) && maxChar >= 3
    if (isValid && (text && text.length > maxChar) || false) {
      let returnText = text.substring(0, maxChar - 3)
      returnText.substr(-1, 3)
      return `${returnText.trim()}...`
    }
    return text
  }

  const checkNested = (obj: any, path: any): any => {
    let arr = path.split('.')
    if (arr.length > 0) {
      if (obj.hasOwnProperty(arr[0])) {
        if (arr.length > 1) return checkNested(obj[arr[0]], arr.splice(1).join('.'))
        else return true
      } else return false
    }
  }

  const getHorizontalAlignment = (alignment: aligment) => {
    if (alignment) {
      let hA = alignment.horizontal
      return alignments.hasOwnProperty(hA) ? alignments[alignment.horizontal] : 'flex-start'
    }
    return 'flex-start'
  }

  const renderText = maxChar ? trimText(text, maxChar) : text

  let containerStyle = Object.assign({
    display: 'inline-flex',
    justifyContent: getHorizontalAlignment(format.alignment)
  }, style)

  return (
    <div style={containerStyle}>
      <span style={{
        color: format.fontColor,
        fontFamily: checkNested(format, 'font.filename') ? `"${format.font.filename.replace('.', '-')}"` : '',
        fontSize: `${format.fontSize}${unit}`,
        textAlign: checkNested(format, 'alignment.horizontal') ? format.alignment.horizontal : 'left',
        lineHeight: lineHeight
      }}>{renderText}</span>
    </div>
  )
}



FormattedText.defaultProps = {
  format: {},
  lineHeight: 1,
  unit: 'vh',
  maxChar: undefined
}
