import Dream from "../../Dream"
import { Container } from "../../Dream/UI"
import { UseAniConfig } from "../types";

/**
 * 递归清除显示对象里面所有的Tween
 * @param obj
 * @param isRecursive 默认true,递归移除子级
 */
export function removeTweens(obj: any, isRecursive: boolean = true) {
  if (!obj) return
  FYGE.Tween.removeTweens(obj);
  if (!isRecursive || !obj.children || !obj.children.length) return
  obj.children.forEach((child: any) => {
      removeTweens(child)
  });
}

export function UseAni(cfg: UseAniConfig) {
  return function(Node: any) {
    return class extends Dream.RenderContainer<{
      getAniIns?: (ins: {
        show: () => Promise<any>
        hide: () => Promise<any>,
        aniCont: FYGE.Container
      }) => any
    }> {
      aniCont: FYGE.Container

      didRendered(): void {
        this.props.getAniIns && this.props.getAniIns({
          show: this.showAni,
          hide: this.hideAni,
          aniCont: this.aniCont
        })

        this.showAni()
      }

      showAni = async () => {
        if (this.aniCont.visible) return
        this.aniCont.visible = true
        this.aniCont.alpha = 1
        if (cfg.showCall) {
          await cfg.showCall(this.aniCont)
        }
      }

      hideAni = async () => {
        if (!this.aniCont.visible) return
        if (cfg.hideCall) {
          await cfg.hideCall(this.aniCont)
        }
        // 清楚 子级的 tween
        removeTweens(this.aniCont)
        this.aniCont.visible = false
      }

      render() {
        const {
          getAniIns,
          ...othersProps
        } = this.props
        return (
          <Container
          ref={el => {
            this.aniCont = el
          }} inlineProps={{
            visible: false
          }}
          className="ani-cont">
            <Node {...othersProps}></Node>
          </Container>
        )
      }
    }
  }
}