import React, { Component } from "react";
import type { StyleProp } from "react-native";
import type { LuraPlayerProps, LuraPlayerState } from "../interfaces";

export default class LuraPlayer extends Component<
  LuraPlayerProps,
  LuraPlayerState
> {
  constructor(props: LuraPlayerProps) {
    super(props);
    this.state = {
      id:
        "player-" +
        (+new Date()).toString(16) +
        Math.floor(Math.random() * 1e8).toString(16),
      player: null,
    };
    this.onScriptLoad = this.onScriptLoad.bind(this);
    this.loadVideo = this.loadVideo.bind(this);
    // @ts-ignore
    if (!window.anvp) {
      // @ts-ignore
      const script = document.createElement("script");
      script.src =
        "https://w3.mp.lura.live/player/3.11.2/v3/scripts/anvload.js";
      script.onload = this.onScriptLoad;
      // @ts-ignore
      document.body.appendChild(script);
    }
  }

  componentDidUpdate(prevProps: Readonly<LuraPlayerProps>): void {
    if (prevProps.token !== this.props.token) {
      this.loadVideo();
    }
  }

  onScriptLoad() {
    // @ts-ignore
    this.state.player = window.AnvatoPlayer(this.state.id);
    this.loadVideo();
  }

  loadVideo() {
    if (!this.state.player || !this.props.token) {
      return;
    }

    const arr = this.props.token.split(".");
    if (arr.length !== 3) {
      return;
    }
    const body = arr[1];
    // @ts-ignore
    const json = JSON.parse(window.atob(body));

    const config = {
      accessKey: json.iss,
      token: this.props.token,
      video: json.vid,
      width: "100%",
    };

    this.state.player.init(config);
  }

  render(): JSX.Element {
    return (
      <div style={this.props.style as StyleProp<any>}>
        <div id={this.state.id} />
      </div>
    );
  }
}
