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

const n = createNamespace('Image');

const Image = ({
    src,
    srcSet,
    className,
    alt,
    withBorder,
    ...otherProps
}) => {
    const imageSrc = (srcSet && (srcSet.default || srcSet['1x'])) || src;

    const excludedSrcset = ['default', '1x'];
    const imageSrcset = srcSet && Object.keys(srcSet).filter(
        key => excludedSrcset.indexOf(key) === -1
    ).reduce((carrySrcSet, key, index) => (
        `${carrySrcSet}${index !== 0 ? ', ' : ''}${srcSet[key]} ${key}`
    ), '');

    return (
        <img
            {...n('item', withBorder && 'bordered').withClass(className).withTestId().props}
            src={imageSrc}
            srcSet={imageSrcset}
            alt={alt}
            {...otherProps}
        />
    );
};


Image.propTypes = {
    className: PropTypes.string,
    alt: PropTypes.string,
    withBorder: PropTypes.bool,
    src: PropTypes.string,
    srcSet: PropTypes.shape({
        default: PropTypes.string,
        '1x': PropTypes.string,
        '2x': PropTypes.string
    })
};

Image.defaultProps = {
    className: '',
    alt: '',
    withBorder: false,
    src: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mO8ff12PQAIMAMONuPA0AAAAABJRU5ErkJggg==',
    srcSet: null
};

export default (Image);
