import React from 'react'
import { isNil } from 'ramda'

function getFirstChar (str) {
  return isNil(str) ? '' : str.substring(0, 1)
}

function getInitials (user) {
  const { firstName, lastName, email } = user
  return isNil(firstName)
    ? getFirstChar(email)
    : `${getFirstChar(firstName)}${getFirstChar(lastName)}`
}

function MTUserImage (props) {
  const {
    user,
    className,
    ...handlers
  } = props

  const hasNoUser = isNil(user)
  const hasNoUserImage = !hasNoUser && isNil(user.image)

  let content
  if (hasNoUser) {
    content = <div className="mt-user-image__initials">?</div>
  } else if (hasNoUserImage) {
    content = <div className="mt-user-image__initials">{ getInitials(user) }</div>
  } else {
    content = <img src={ user.image } alt="" />
  }

  return (
    <div
      className={ `mt-user-image ${className}` }
      { ...handlers }
    >
      { content }
    </div>
  )
}

export default MTUserImage
