// 在头部添加此行来确保类定义之后可以访问全局NodePlayer对象
let NodePlayer;

if (typeof window !== 'undefined') {
  NodePlayer = window.NodePlayer;
}
/**
 * 直播播放器
 * @param {string} elementId 元素Id
 * @param {string} url 直播地址
 */
export class LivePlayer {
  constructor(elementId, url) {
    this.elementId = elementId;
    this.url = url;
    if (typeof window.NodePlayer !== 'undefined') {
      this._init();
    } else {
      const nodePlayerCheckInterval = setInterval(() => {
        if (window.nodePlayerLoaded) {
          clearInterval(nodePlayerCheckInterval);
          this._init();
        }
      }, 100);
    }
  }

  /**
   * 全局初始化
   * @returns {Promise<void>}
   */
  static init() {
    return new Promise((resolve, _) => {
      window.NodePlayer.load(() => {
        //v0.5.70版之后,在Android手机端推荐使用以下音频引擎
        if (/(Android)/i.test(navigator.userAgent)) {
          window.NodePlayer.activeAudioEngine(true);
        }
        resolve();
      });
    });
  }

  /**
   * 播放
   * @param {bool} keepRetry 保持重试
   */
  play(keepRetry = true) {
    this._keepRetry = keepRetry;
    this._nplayer.start(this.url);
  }

  /**
   * 停止
   */
  stop() {
    this._keepRetry = false; //关闭重试
    this._nplayer.stop();
  }

  enableAudio(keepEnableAudio = true) {
    this._nplayer.enableAudio(keepEnableAudio);
  }

  audioResume() {
    this._nplayer.audioResume();
  }
  clearView() {
    this._nplayer.clearView();
  }
  releasePlayer() {
    this._nplayer.release();
  }
  fullscreen() {
    this._nplayer.fullscreen();
  }

  /**
   * 通知底层重新计算渲染尺寸
   * @param {number} rotate - 旋转角度 默认0，可设90，270，旋转画面。
   */
  onResize(rotate) {
    this._nplayer.onResize(rotate);
  }

  _init() {
    this._retryCount = 0;
    const player = new window.NodePlayer();
    this._nplayer = player;
    // this._initState();

    // 开启屏幕常亮
    player.setKeepScreenOn();
    // 绑定dom
    player.setView(this.elementId);
    // 设置最大缓冲时长，单位毫秒
    player.setBufferTime(1000);
    // 设置超时时长, 单位秒；回调timeout事件
    player.setTimeout(2);
    // 缩放模式，0 fill，1 contain，2 cover
    player.setScaleMode(1);
    // 开始音频
    player.enableAudio(true);

    player.on('videoInfo', (w, h, codec) => {
      if (!!this.onInfo) {
        this.onInfo({ width: w, height: h });
      }
    });
    player.on('videoFrame', (pts) => {
      /// 每一帧执行一次视频处理
      this.onFrame && this.onFrame();
    });
    player.on('timeout', () => {
      this.onTimeout && this.onTimeout();
    });
    player.on('start', () => {
      this.onPlay && this.onPlay();
    });
    player.on('stop', () => {
      this.onStop && this.onStop();
      this._onStop();
    });
    player.on('buffer', (state) => {
      this.onBuffer && this.onBuffer(state);
    });
    player.on('stats', (stats) => {
      if (stats.abps === 0 && stats.fps === 0 && stats.vbps === 0) {
        this._tryReConnect();
      }
    });
    player.on('error', (error) => {
      this.onError && this.onError(error);
    });
  }

  _onStop() {
    const retry = this._keepRetry;
    if (retry === true) {
      if (this._retryCount > 800) return;
      setTimeout(() => {
        this._retryCount += 1;
        this.play(retry);
      }, 800);
    }
  }

  /// 尝试断线后重连
  _tryReConnect() {
    this.releasePlayer();
    this._init();
    this.play(true);
  }
}
