import { Eventer } from "@tingwujs/common";
import { PID } from "@tingwujs/core";
import { getDirection } from "../utils/direction";

export interface PlayingWordControllerEventes {
  playingParagraphVisibleChange: {
    enable: boolean;
    visible?: boolean;
    direction?: "top" | "bottom";
  };
  paragraphShowUp: {
    pid: PID;
    force?: boolean; // 如果为true，则不计算边界，始终会滚动到指定位置
    seekWithExtContent?: boolean;
  };
}

export class PlayingWordController extends Eventer<PlayingWordControllerEventes> {
  calcPlayingWordVisible(
    playingParagraphTop: number,
    playingParagraphHeight: number,
    scrollTop: number,
    scrollViewHeight: number
  ) {
    const playingParagraphBottom = playingParagraphTop + playingParagraphHeight;
    const scrollBottom = scrollTop + scrollViewHeight;

    const direction = getDirection(
      playingParagraphTop,
      playingParagraphBottom,
      scrollTop,
      scrollBottom
    );

    if (direction) {
      this.emit("playingParagraphVisibleChange", {
        enable: true,
        visible: false,
        direction,
      });
    } else {
      this.emit("playingParagraphVisibleChange", {
        enable: true,
        visible: true,
      });
    }
  }

  disablePlayingWord() {
    this.emit("playingParagraphVisibleChange", {
      enable: false,
    });
  }
}
