import Dream from "../../Dream";
import { RenderContainer } from "../../Dream/renderContainer"
import { UseAniConfig, UsePreloadType } from "../types";
import { removeALLTweens } from "../utils";

type SignleContainer = FYGE.Container

type TagType = SignleContainer | RenderContainer | (FC)

type FC<P = {}> = FunctionComponent<P>;

type PropsWithChildren<P> = P & { children?: any[] };

interface FunctionComponent<P = {}> {
    (props: PropsWithChildren<P>): SignleContainer;
}

interface SceneCompent {
  destroy(): void
}

type SceneConfig = UsePreloadType & UseAniConfig

function SceneWrapper(SceneNode: any) {
  return class extends Dream.RenderContainer<{
    onLoaded: (m: any) => any
  }>{
    sceneContainer: FYGE.Container
    wrapperContainer: FYGE.Container

    // 做锤子动画
    show() {
      // 做动画
      this.wrapperContainer.visible = true
    }

    hide() {
      this.wrapperContainer.visible = false
    }

    destroy() {
      const scene = this.wrapperContainer 
      // 还是全部现清一遍吧， 不知道里面的 removeChild 会不会去处理
      // removeALLTweens(scene)
      // 清除掉自己
      scene.parent.removeChild(scene)
      scene.destroy()
    }

    render() {
      const {
        onLoaded, ...otherProps
      } = this.props
      return (
        <FYGE.Container ref={(el: any) => this.wrapperContainer = el}>
          <FYGE.Container ref={(el: FYGE.Container) => this.sceneContainer = el}>
            <SceneNode {...otherProps} ref={(el: any) => {
              // 预加载组建的话 走onLoaded
              if (el.dreamType !== 'preloadComponent') {
                this.props.onLoaded(this)
              }
            }} onLoaded={() => {
              this.props.onLoaded(this)
            }}></SceneNode>
          </FYGE.Container>
        </FYGE.Container>
      )
    }
  }
}

export const SceneController = (function() {
  let controller: FYGE.Container
  let preScene: SceneCompent // 之前一个场景的
  return {
    init(cont: FYGE.Container) {
      controller = cont
    },
    destroyScene(scene: SceneCompent) {
      scene.destroy()
    },
    changeScene(SceneNode: any, props?: Record<string, any>) {
      console.log('controller===', controller)
      if (!controller) {
        throw new Error('没有场景controller')
      }
      const S = SceneWrapper(SceneNode)
      const cont = new FYGE.Container()
      controller.addChild(cont)
      Dream.VirtualRender(cont, <S
        {...props}
        onLoaded={(el) => {
          preScene && preScene.destroy()
          preScene = el
        }}
      ></S>)
    }
  }
})()