import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import { isEditableVectorImage, getPreviewUrlFromImageData } from 'App/Reducers/ImageGallery/Selectors';
import { getSvgContent, applySvgContentOperations } from 'App/Services/DesignDataService';
import { getRasterURL } from '../../Utils/Transformers';

const styles = () => ({
    image: ({ image }) => ({
        width: '100%',
        height: '100%',
        objectFit: 'contain',
        background: image.thumbnail && image.thumbnail.isThumbnailBright ? '#c4c4c4' : 'transparent',
    }),
});

class ImageThumbnail extends React.Component {
    static propTypes = {
        classes: PropTypes.object,
        image: PropTypes.object,
    };

    constructor(props) {
        super(props);

        this.state = {
            src: null,
        };
    }

    componentDidMount() {
        this.setState({
            src: this.getSrc(),
        });
    }

    componentDidUpdate(prevProps) {
        const { image } = this.props;

        if (image !== prevProps.image) {
            this.setState({
                src: this.getSrc(),
            });
        }
    }

    getSrc() {
        const { image } = this.props;

        if (!isEditableVectorImage(image.preview)) {
            return image.url;
        }

        if (!image.displayColorPreview && !image.gallery) {
            return getRasterURL(getPreviewUrlFromImageData(image.thumbnail));
        }

        this.downloadSvg(image);

        return null;
    }

    async downloadSvg(image) {
        const svgContent = await getSvgContent(getPreviewUrlFromImageData(image.preview), true);

        this.setState({
            src: applySvgContentOperations(image.original, image.preview, image.operations, svgContent),
        });
    }

    render() {
        const { classes } = this.props;
        const { src } = this.state;

        return src === null ? null : <img src={src} className={classes.image} />;
    }
}

export default withStyles(styles, { name: 'ImageThumbnail' })(ImageThumbnail);
