import * as React from 'react';
import classnames from 'classnames';
import {Spinner} from '../Spinner';
import {FlexBlock} from '../flexBlock';

export type CardImageProps = {
    url: string;
    cover?: boolean;
};

type CardImageState = {
    loaded: boolean;
};

export class CardImage extends React.PureComponent<CardImageProps, CardImageState> {
    state = {
        loaded: false
    };

    componentWillMount() {
        this.loadImage();
    }

    componentDidUpdate(prevProps: Readonly<CardImageProps>): void {
        if (prevProps.url !== this.props.url) {
            this.loadImage();
        }
    }

    loadImage() {
        const {url} = this.props;
        const {loaded} = this.state;

        if (loaded) {
            this.setState({
                loaded: false
            });
        }

        const image = new Image();

        image.addEventListener('load', () => {
            this.setState({
                loaded: true
            });
        });

        image.src = url;
    }

    renderContent() {
        const {url, cover} = this.props;
        const {loaded} = this.state;

        if (!loaded) {
            return <Spinner size={24} />;
        }

        const className = classnames('rc-card__image', {
            'rc-card__image--cover': cover
        });

        return <img src={url} className={className} />;
    }

    render() {
        return (
            <FlexBlock
                className="rc-card__image-placeholder"
                align={FlexBlock.CENTER}
                justify={FlexBlock.CENTER}
                gutterWidth={0}>
                {this.renderContent()}
            </FlexBlock>
        );
    }
}
