import React, { Component } from "react";
import { getSDK, isMediaStream } from "../utils.js";
const IOS = typeof navigator !== "undefined" && /iPad|iPhone|iPod/.test(navigator.userAgent) && // @ts-expect-error
!window.MSStream;
const AUDIO_EXTENSIONS = /\.(m4a|mp4a|mpga|mp2|mp2a|mp3|m2a|m3a|wav|weba|aac|oga|spx)($|\?)/i;
const VIDEO_EXTENSIONS = /\.(mp4|og[gv]|webm|mov|m4v)($|\?)/i;
const HLS_EXTENSIONS = /\.(m3u8)($|\?)/i;
const HLS_SDK_URL = "https://cdn.jsdelivr.net/npm/hls.js@VERSION/dist/hls.min.js";
const HLS_GLOBAL = "Hls";
const DASH_EXTENSIONS = /\.(mpd)($|\?)/i;
const DASH_SDK_URL = "https://cdnjs.cloudflare.com/ajax/libs/dashjs/VERSION/dash.all.min.js";
const DASH_GLOBAL = "dashjs";
const MATCH_DROPBOX_URL = /www\.dropbox\.com\/.+/;
function canPlay(url) {
  if (url instanceof Array) {
    for (const item of url) {
      if (typeof item === "string" && canPlay(item)) {
        return true;
      }
      if (canPlay(item.src)) {
        return true;
      }
    }
    return false;
  }
  if (isMediaStream(url)) {
    return true;
  }
  return AUDIO_EXTENSIONS.test(url) || VIDEO_EXTENSIONS.test(url) || HLS_EXTENSIONS.test(url) || DASH_EXTENSIONS.test(url);
}
function supportsWebKitPresentationMode(video) {
  if (!video) {
    video = document.createElement("video");
  }
  return video.webkitSupportsPresentationMode && typeof video.webkitSetPresentationMode === "function" && !/iPhone|iPod/.test(navigator.userAgent);
}
function canEnablePIP(url) {
  return canPlay(url) && // @ts-expect-error
  (!!document.pictureInPictureEnabled || supportsWebKitPresentationMode()) && !AUDIO_EXTENSIONS.test(url);
}
class FilePlayer extends Component {
  constructor() {
    super(...arguments);
    // Proxy methods to prevent listener leaks
    this.onReady = (...args) => this.props.onReady(...args);
    this.onPlay = (...args) => this.props.onPlay(...args);
    this.onBuffer = (...args) => this.props.onBuffer(...args);
    this.onBufferEnd = (...args) => this.props.onBufferEnd(...args);
    this.onPause = (...args) => this.props.onPause(...args);
    this.onEnded = (...args) => this.props.onEnded(...args);
    this.onError = (...args) => this.props.onError(...args);
    this.onEnablePIP = (...args) => this.props.onEnablePIP(...args);
    this.onDisablePIP = (e) => {
      const { onDisablePIP, playing } = this.props;
      onDisablePIP(e);
      if (playing) {
        this.play();
      }
    };
    this.onPresentationModeChange = (e) => {
      if (this.player && supportsWebKitPresentationMode(this.player)) {
        const { webkitPresentationMode } = this.player;
        if (webkitPresentationMode === "picture-in-picture") {
          this.onEnablePIP(e);
        } else if (webkitPresentationMode === "inline") {
          this.onDisablePIP(e);
        }
      }
    };
    this.onSeek = (e) => {
      this.props.onSeek(e.target.currentTime);
    };
    this.mute = () => {
      this.player.muted = true;
    };
    this.unmute = () => {
      this.player.muted = false;
    };
    this.renderSourceElement = (source, index) => {
      if (typeof source === "string") {
        return /* @__PURE__ */ React.createElement("source", { key: index, src: source });
      }
      return /* @__PURE__ */ React.createElement("source", { key: index, ...source });
    };
    this.renderTrack = (track, index) => {
      return /* @__PURE__ */ React.createElement("track", { key: index, ...track });
    };
    this.ref = (player) => {
      if (this.player) {
        this.prevPlayer = this.player;
      }
      this.player = player;
    };
  }
  componentDidMount() {
    this.addListeners(this.player);
    if (IOS) {
      this.player.load();
    }
  }
  componentDidUpdate(prevProps) {
    if (this.shouldUseAudio(this.props) !== this.shouldUseAudio(prevProps)) {
      this.removeListeners(this.prevPlayer);
      this.addListeners(this.player);
    }
  }
  componentWillUnmount() {
    this.removeListeners(this.player);
    if (this.hls) {
      this.hls.destroy();
    }
  }
  addListeners(player) {
    const { playsinline } = this.props;
    player.addEventListener("canplay", this.onReady);
    player.addEventListener("play", this.onPlay);
    player.addEventListener("waiting", this.onBuffer);
    player.addEventListener("playing", this.onBufferEnd);
    player.addEventListener("pause", this.onPause);
    player.addEventListener("seeked", this.onSeek);
    player.addEventListener("ended", this.onEnded);
    player.addEventListener("error", this.onError);
    player.addEventListener("enterpictureinpicture", this.onEnablePIP);
    player.addEventListener("leavepictureinpicture", this.onDisablePIP);
    player.addEventListener("webkitpresentationmodechanged", this.onPresentationModeChange);
    if (playsinline) {
      player.setAttribute("playsinline", "");
      player.setAttribute("webkit-playsinline", "");
      player.setAttribute("x5-playsinline", "");
    }
  }
  removeListeners(player) {
    player.removeEventListener("canplay", this.onReady);
    player.removeEventListener("play", this.onPlay);
    player.removeEventListener("waiting", this.onBuffer);
    player.removeEventListener("playing", this.onBufferEnd);
    player.removeEventListener("pause", this.onPause);
    player.removeEventListener("seeked", this.onSeek);
    player.removeEventListener("ended", this.onEnded);
    player.removeEventListener("error", this.onError);
    player.removeEventListener("enterpictureinpicture", this.onEnablePIP);
    player.removeEventListener("leavepictureinpicture", this.onDisablePIP);
    player.removeEventListener("webkitpresentationmodechanged", this.onPresentationModeChange);
  }
  shouldUseAudio(props) {
    if (props.config.file.forceVideo) {
      return false;
    }
    if (props.config.file.attributes.poster) {
      return false;
    }
    return AUDIO_EXTENSIONS.test(props.url) || props.config.file.forceAudio;
  }
  shouldUseHLS(url) {
    return HLS_EXTENSIONS.test(url) && !IOS || this.props.config.file.forceHLS;
  }
  shouldUseDASH(url) {
    return DASH_EXTENSIONS.test(url) || this.props.config.file.forceDASH;
  }
  load(url) {
    const { hlsVersion, dashVersion } = this.props.config.file;
    if (this.shouldUseHLS(url)) {
      getSDK(HLS_SDK_URL.replace("VERSION", hlsVersion), HLS_GLOBAL).then((Hls) => {
        this.hls = new Hls(this.props.config.file.hlsOptions);
        this.hls.on(Hls.Events.ERROR, (e, data) => {
          this.props.onError(e, data, this.hls, Hls);
        });
        this.hls.loadSource(url);
        this.hls.attachMedia(this.player);
      });
    }
    if (this.shouldUseDASH(url)) {
      getSDK(DASH_SDK_URL.replace("VERSION", dashVersion), DASH_GLOBAL).then((dashjs) => {
        this.dash = dashjs.MediaPlayer().create();
        this.dash.initialize(this.player, url, this.props.playing);
        this.dash.on("error", this.props.onError);
        this.dash.getDebug().setLogToBrowserConsole(false);
      });
    }
    if (url instanceof Array) {
      this.player.load();
    } else if (isMediaStream(url)) {
      try {
        this.player.srcObject = url;
      } catch {
        this.player.src = window.URL.createObjectURL(url);
      }
    }
  }
  play() {
    const promise = this.player.play();
    if (promise) {
      promise.catch(this.props.onError);
    }
  }
  pause() {
    this.player.pause();
  }
  stop() {
    this.player.removeAttribute("src");
    if (this.dash) {
      this.dash.reset();
    }
  }
  seekTo(seconds) {
    this.player.currentTime = seconds;
  }
  setVolume(fraction) {
    this.player.volume = fraction;
  }
  enablePIP() {
    if (this.player.requestPictureInPicture && document.pictureInPictureElement !== this.player) {
      this.player.requestPictureInPicture();
    } else if (supportsWebKitPresentationMode(this.player) && this.player.webkitPresentationMode !== "picture-in-picture") {
      this.player.webkitSetPresentationMode("picture-in-picture");
    }
  }
  disablePIP() {
    if (document.exitPictureInPicture && document.pictureInPictureElement === this.player) {
      document.exitPictureInPicture();
    } else if (supportsWebKitPresentationMode(this.player) && this.player.webkitPresentationMode !== "inline") {
      this.player.webkitSetPresentationMode("inline");
    }
  }
  setPlaybackRate(rate) {
    this.player.playbackRate = rate;
  }
  getDuration() {
    if (!this.player) {
      return null;
    }
    const { duration, seekable } = this.player;
    if (duration === Infinity && seekable.length > 0) {
      return seekable.end(seekable.length - 1);
    }
    return duration;
  }
  getCurrentTime() {
    if (!this.player) {
      return null;
    }
    return this.player.currentTime;
  }
  getSecondsLoaded() {
    if (!this.player) {
      return null;
    }
    const { buffered } = this.player;
    if (buffered.length === 0) {
      return 0;
    }
    const end = buffered.end(buffered.length - 1);
    const duration = this.getDuration();
    if (end > duration) {
      return duration;
    }
    return end;
  }
  getSource(url) {
    const useHLS = this.shouldUseHLS(url);
    const useDASH = this.shouldUseDASH(url);
    if (url instanceof Array || isMediaStream(url) || useHLS || useDASH) {
      return void 0;
    }
    if (MATCH_DROPBOX_URL.test(url)) {
      return url.replace("www.dropbox.com", "dl.dropboxusercontent.com");
    }
    return url;
  }
  render() {
    const { url, playing, loop, controls, muted, config, width, height } = this.props;
    const useAudio = this.shouldUseAudio(this.props);
    const Element = useAudio ? "audio" : "video";
    const style = {
      width: width === "auto" ? width : "100%",
      height: height === "auto" ? height : "100%"
    };
    if (!useAudio) {
      style.display = "block";
    }
    return /* @__PURE__ */ React.createElement(
      Element,
      {
        ref: this.ref,
        src: this.getSource(url),
        style,
        preload: "auto",
        autoPlay: playing || void 0,
        controls,
        muted,
        loop,
        ...config.file.attributes
      },
      url instanceof Array && url.map(this.renderSourceElement),
      config.file.tracks.map(this.renderTrack)
    );
  }
}
FilePlayer.displayName = "FilePlayer";
FilePlayer.canPlay = canPlay;
FilePlayer.canEnablePIP = canEnablePIP;
export {
  FilePlayer
};
//# sourceMappingURL=file-player.js.map
