import React, { useEffect, useRef, useState } from 'react';
import { MediaProps } from '.';
import { jsonProxy2, revokeJsonProxy } from '@/utils/constants';

const Audio: React.FC<MediaProps> = ({ media, autoPlay, getMedia }) => {
  const [hasChangedProxy, setHasChangedProxy] = useState(false);
  const [hasRemovedProxy, setHasRemovedProxy] = useState(false);
  const audio = useRef<HTMLAudioElement>(null);
  useEffect(() => {
    getMedia?.(audio.current);
  }, [getMedia]);
  return (
    <div className="audioContainer">
      <audio
        className="audio"
        ref={audio}
        controls
        loop
        src={media}
        autoPlay={autoPlay}
        onError={el => {
          if (!hasRemovedProxy) {
            el.currentTarget.src = revokeJsonProxy(el.currentTarget.src);
            const el2 = el.currentTarget;
            const pNode = el.currentTarget.parentNode;
            el.currentTarget.remove();
            pNode?.append(el2);
            setHasRemovedProxy(true);
          } else if (!hasChangedProxy) {
            el.currentTarget.src = jsonProxy2(el.currentTarget.src);
            const el2 = el.currentTarget;
            const pNode = el.currentTarget.parentNode;
            el.currentTarget.remove();
            pNode?.append(el2);
            setHasChangedProxy(true);
          }
        }}
      />
    </div>
  );
};

export default Audio;
