import React, { Component } from "react";
import { callPlayer, getSDK, randomString } from "../utils.js";
const SDK_URL = "https://player.twitch.tv/js/embed/v1.js";
const SDK_GLOBAL = "Twitch";
const MATCH_VIDEO_URL = /(?:www\.|go\.)?twitch\.tv\/videos\/(\d+)($|\?)/;
const MATCH_CHANNEL_URL = /(?:www\.|go\.)?twitch\.tv\/([a-z0-9_]+)($|\?)/;
const PLAYER_ID_PREFIX = "twitch-player-";
class Twitch extends Component {
  constructor() {
    super(...arguments);
    this.callPlayer = callPlayer;
    this.playerID = this.props.config.twitch.playerId || `${PLAYER_ID_PREFIX}${randomString()}`;
    this.mute = () => {
      this.callPlayer("setMuted", true);
    };
    this.unmute = () => {
      this.callPlayer("setMuted", false);
    };
  }
  load(url, isReady) {
    const { playsinline, onError, config, controls } = this.props;
    const isChannel = MATCH_CHANNEL_URL.test(url);
    const id = isChannel ? url.match(MATCH_CHANNEL_URL)[1] : url.match(MATCH_VIDEO_URL)[1];
    if (isReady) {
      if (isChannel) {
        this.player.setChannel(id);
      } else {
        this.player.setVideo("v" + id);
      }
      return;
    }
    getSDK(SDK_URL, SDK_GLOBAL).then((Twitch2) => {
      this.player = new Twitch2.Player(this.playerID, {
        video: isChannel ? "" : id,
        channel: isChannel ? id : "",
        height: "100%",
        width: "100%",
        playsinline,
        autoplay: this.props.playing,
        muted: this.props.muted,
        // https://github.com/CookPete/react-player/issues/733#issuecomment-549085859
        controls: isChannel ? true : controls,
        ...config.twitch.options
      });
      const { READY, PLAYING, PAUSE, ENDED, ONLINE, OFFLINE } = Twitch2.Player;
      this.player.addEventListener(READY, this.props.onReady);
      this.player.addEventListener(PLAYING, this.props.onPlay);
      this.player.addEventListener(PAUSE, this.props.onPause);
      this.player.addEventListener(ENDED, this.props.onEnded);
      this.player.addEventListener(ONLINE, this.props.onLoaded);
      this.player.addEventListener(OFFLINE, this.props.onLoaded);
    }, onError);
  }
  play() {
    this.callPlayer("play");
  }
  pause() {
    this.callPlayer("pause");
  }
  stop() {
    this.callPlayer("pause");
  }
  seekTo(seconds) {
    this.callPlayer("seek", seconds);
  }
  setVolume(fraction) {
    this.callPlayer("setVolume", fraction);
  }
  getDuration() {
    return this.callPlayer("getDuration");
  }
  getCurrentTime() {
    return this.callPlayer("getCurrentTime");
  }
  getSecondsLoaded() {
    return null;
  }
  render() {
    const style = {
      width: "100%",
      height: "100%"
    };
    return /* @__PURE__ */ React.createElement("div", { style, id: this.playerID, loading: "lazy" });
  }
}
Twitch.displayName = "Twitch";
Twitch.canPlay = (url) => MATCH_VIDEO_URL.test(url) || MATCH_CHANNEL_URL.test(url);
Twitch.loopOnEnded = true;
export {
  Twitch
};
//# sourceMappingURL=twitch.js.map
