import React, {Fragment, useEffect, useState} from "react";
import {ReactComponent as DiscSVG} from "../svg/disc.svg";
import {getDiscCoverArt} from "../services/entity_service";

export const CoverArt = (props) => {
    const disc = props.disc
    const [loading, setLoading] = useState(true);
    const [coverArt, setCoverArt] = useState(null)

    useEffect(() => {
        if(disc){
            getDiscCoverArt(disc.id).then((result) => {
                setCoverArt(result)
            })
        }
    }, [disc])

    const handleLoad = () => setLoading(false)

    if (coverArt) {
        if (loading) {
            return (
                <Fragment>
                    <img src={coverArt.image} className={'coverart loading'} alt={props.alt} onLoad={handleLoad}/>
                    <div className={'coverart pulsating'}/>
                </Fragment>
            )
        } else {
            return <img src={coverArt.image} className={'coverart'} alt={props.alt}/>
        }
    } else {
        return <DiscSVG className='coverart'/>
    }
}


export const CoverWithCaption = (props) => {
   return(
       <figure className='cover-caption'>
           <CoverArt disc={props.disc} alt={props.alt}/>
           <figcaption>{props.caption}</figcaption>
       </figure>
   );
}
