import * as React from 'react';
import { createRoot } from 'react-dom/client';
import AudioController from '../AudioController';
import { markType } from '../control';

class MediaController {
  private mediaControllerRef: any = null; // 控制条

  constructor(
    audio: any,
    ele: HTMLElement,
    controlParams: any,
    model?: string,
    rssItemInfo?: any,
  ) {
    this.mediaControllerRef = this.createControlBar(
      audio,
      ele,
      controlParams,
      model,
      rssItemInfo,
    );
  }

  protected createControlBar = (
    audio: any,
    ele: HTMLElement,
    controls: any,
    model?: string,
    rssItemInfo?: any,
  ) => {
    // if (!audio.id) return;

    let controlParams = {};
    if (controls !== true) {
      controlParams = {
        ...controlParams,
        ...controls,
      };
    }
    const controllerWrapper = document.createElement('div');
    controllerWrapper.style.width = '100%';
    controllerWrapper.style.height = '100%';
    const controllerRef = React.createRef();

    const controllerBar = React.createElement(
      (model = AudioController as any),
      {
        ref: controllerRef,
        ...controlParams,
        audio,
        rssItemInfo,
      },
    );
    const root = createRoot(controllerWrapper);
    root.render(controllerBar);
    // ReactDOM.render(controllerBar, controllerWrapper);
    ele.appendChild(controllerWrapper);

    return controllerRef;
  };

  set controlsCur(value) {
    this.mediaControllerRef && (this.mediaControllerRef.current = value);
  }

  get controlsCur() {
    return this.mediaControllerRef?.current;
  }

  private toggleShortcutKey = (open: boolean) => {
    this.controlsCur?.setShortcutKey(open);
  };

  // 高亮某个标记
  highlightMark = (type: markType, index: number) => {
    if (typeof index !== 'number') return;
    if (type === 'segment') {
      this.controlsCur?.setHltMarkSegIndex(index);
    }
    if (type === 'point') {
      this.controlsCur?.setHltMarkPointIndex(index);
    }
  };

  // 新增打标
  setMarkPointList = (markPointList: any) => {
    this.controlsCur?.setMarkPointList(markPointList);
  };

  // 新增章节速览
  setMarkSegmentList = (markSegmentList: any) => {
    this.controlsCur?.setMarkSegmentList(markSegmentList);
  };

  // 跳转到时间提示
  setJumpTipsTime = (val: string) => {
    this.controlsCur?.setJumpTipsTime(val);
  };
}

export default MediaController;
