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

const n = createNamespace('Image');

const Image = React.forwardRef(({
    src,
    srcSet,
    className,
    alt,
    withBorder,
    ...otherProps
}, ref) => {
    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}
            ref={ref}
            {...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: DEFAULT_IMG,
    srcSet: null
};

export default (Image);
