import React, {useState} from 'react';
import {AvatarStyle as S} from './styles/avatar.style';
import {IAvatar} from './avatar.type';
import {avatarPlaceholderSelector as placeholderSelector} from './helpers/avatar-placeholder-selector';
import {AvatarWrapperComponent as Wrapper} from './parts/wrapper/avatar-wrapper.component';

export const AvatarComponent: React.FC<IAvatar> = (props) => {
    const {src, placeholder, unlimitedPlaceholder} = props;
    const [error, setError] = useState<boolean>(false);
    const onError = () => setError(true);

    if (src && !error)
        return (
            <Wrapper {...props}>
                <S.Picture src={src} onError={onError} />
            </Wrapper>
        );

    if (!src && placeholder)
        return (
            <Wrapper {...props}>
                <S.Text>
                    {unlimitedPlaceholder
                        ? placeholder
                        : placeholderSelector(placeholder)}
                </S.Text>
            </Wrapper>
        );

    return (
        <Wrapper {...props}>
            <S.Icon />
        </Wrapper>
    );
};
