import React from 'react';
import uniqolor from 'uniqolor';

import '../styles/avatar.css';

export const Avatar = ({ source, name, size, hash }) => {
    if (source){
        return (
            <img 
                className="avatar" 
                style={{width: size, height: size}}
                src={source}
                title={name}
            />
        );
    } else {

        if (name){
            var backgroundColor = uniqolor(name, {
                saturation: 90,
                lightness: [80, 90],
            })
        
            var { color } = uniqolor(name)

            var initials = name.match(/\b\w/g) || [];
            initials = ((initials.shift() || '') + (initials.pop() || '')).toUpperCase();

        } else {

            var initials = '?'

            if (hash){
                var backgroundColor = uniqolor(hash, {
                    saturation: 90,
                    lightness: [80, 90],
                })
        
                var { color } = uniqolor(hash)
            } else {
                var backgroundColor = uniqolor.random({
                    saturation: 90,
                    lightness: [80, 90],
                })
        
                var { color } = uniqolor.random()
            } 
        }

        return (
            <div
                className="avatar" 
                style={{width: size, height: size, backgroundColor: backgroundColor.color}}
                src={source}
                title={name || 'Anonymous'}
            >
                <label className="initials" style={{ color: color }}>
                    {initials}
                </label>
            </div>
        );
    }
    
}