import React from 'react';
import PropTypes from 'prop-types';
import { createNamespace } from '../../tools/namingTools';
import { DEFAULT_IMG } from '../../constants/images';
import { getImageSrc } from '../../tools/images';
// IMPORTANT: (s)css should be imported after other atoms/components
import './styles/Image.scss';

const n = createNamespace('Image');

const Image = React.forwardRef(({
    src,
    srcSet,
    className,
    alt,
    withBorder,
    isCopyRighted,
    ...otherProps
}, ref) => {
    const imageSrc = getImageSrc(src, srcSet);
    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', isCopyRighted && 'copyRighted']).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
    }),
    isCopyRighted: PropTypes.bool
};

Image.defaultProps = {
    className: '',
    alt: '',
    withBorder: false,
    src: DEFAULT_IMG,
    srcSet: null,
    isCopyRighted: false
};

export default (Image);
