import React from 'react';
import PropTypes from 'prop-types';
import './styles/Avatar.scss';
import { createNamespace } from '../../tools/namingTools';
import Image from '../image/Image';

const n = createNamespace('Avatar');
const getNameInitials = fullName => fullName && fullName.match(/\b(\w)/g).map(letter => letter.toUpperCase()).join('');

const Avatar = ({
    name,
    className,
    picture,
    size,
    borderRadius,
    ...otherProps
}) => {
    // show picture or initials when picture is missing
    let content = null;
    if (picture) {
        content = <Image src={picture} alt={name} {...n('image').props} />;
    } else {
        content = <span {...n('initial').withTestId().props} aria-hidden="true">{getNameInitials(name)}</span>;
    }

    const cssVariables = {
        size: size && `${size}px`,
        'border-radius': borderRadius && `${borderRadius}px`
    };
    const wrapperModifier = picture ? 'with-picture' : 'with-initials';
    const specificProps = n('wrapper', wrapperModifier).withClass(className).withVariables(cssVariables).withTestId().props;

    return (
        <div {...otherProps} {...specificProps}>{content}</div>
    );
};

Avatar.propTypes = {
    className: PropTypes.string,
    name: PropTypes.string,
    picture: PropTypes.string,
    size: PropTypes.number,
    borderRadius: PropTypes.number
};

Avatar.defaultProps = {
    className: '',
    name: '',
    picture: null,
    size: null,
    borderRadius: null
};

export default Avatar;
