import * as React from 'react';

import { logger } from 'tachyon-logger';

export interface BaseVideoPlayerProps {
  sessionID: string;
  hostChannel?: string;
}

export abstract class BaseVideoPlayer<
  P extends BaseVideoPlayerProps
> extends React.PureComponent<P, {}> {
  player: Twitch.Player | undefined;
  holder: HTMLDivElement;

  latencyEventName: string = 'contentShowing'; // secret event showing player rendered
  latencyEventTarget: Twitch.Player | undefined;

  abstract get playerParams(): Partial<Twitch.PlayerOptions>;
  abstract trackPlayerReady: EventListener;
  abstract trackPlayerPlaying: EventListener;

  componentDidMount(): void {
    this.buildPlayer();
  }

  componentWillUnmount(): void {
    if (this.player) {
      this.player.removeEventListener(
        window.Twitch.Player.READY,
        this.onPlayerReady,
      );
      this.player.removeEventListener(
        window.Twitch.Player.READY,
        this.trackPlayerReady,
      );
      this.player.removeEventListener(
        window.Twitch.Player.PLAYING,
        this.trackPlayerPlaying,
      );
    }
  }

  render(): React.ReactElement<any> {
    return (
      <div className="dynamic-player video">
        <div
          ref={c => (this.holder = c as HTMLDivElement)}
          className="player-holder video qa-player-holder"
        />
      </div>
    );
  }

  onPlayerReady = () => {
    if (this.player) {
      this.player.setTrackingProperties({
        app_session_id: this.props.sessionID,
        benchmark_session_id: this.props.sessionID,
        client_app: 'mobile_web',
        host_channel: this.props.hostChannel,
      });
    }
  };

  protected buildPlayer(): void {
    try {
      this.player = new window.Twitch.Player(this.holder, {
        ...this.playerParams,
        width: '100%',
        height: '100%',
        branding: false,
        channelInfo: false,
        allowfullscreen: true,
        playsinline: true,
        muted: true,
        autoplay: true,
      });
      this.latencyEventTarget = this.player;

      this.player.addEventListener(
        window.Twitch.Player.READY,
        this.onPlayerReady,
      );
      this.player.addEventListener(
        window.Twitch.Player.READY,
        this.trackPlayerReady,
      );
      this.player.addEventListener(
        window.Twitch.Player.PLAYING,
        this.trackPlayerPlaying,
      );
    } catch (error) {
      logger.error({ message: 'Error building player', error });
    }
  }
}
