import * as React from "react"
import * as Pixi from "pixi.js"

interface IMainProps {}
interface IMainState {}
export default class PixiComponent extends React.Component<
  IMainProps,
  IMainState
> {
  public app: Pixi.Application
  public gameCanvas: HTMLDivElement

  constructor(props) {
    super(props)
  }

  public componentDidMount() {
    this.app = new Pixi.Application({
      width: window.innerWidth,
      height: window.innerHeight,
      backgroundColor: 0xffffff
    })
    // this.app = new Pixi.Application(window.innerWidth, window.innerHeight);
    // this.app.renderer.backgroundColor = 0xff00cc;
    this.gameCanvas.appendChild(this.app.view)

    Pixi.loader
      .add("bubble", "/ui-assets/images/adore/sprite-heart-orange.png")
      .load((loader, resources) => {
        let frames: any[] = []
        for (let i = 1; i <= 11; i++) {
          const val = i < 10 ? "0" + i : i
          frames.push(
            Pixi.Texture.fromImage(
              "/ui-assets/images/adore/heart-orange/effect" + val + ".png"
            )
          )
        }
        frames.push(Pixi.Texture.EMPTY)
        const anim = new Pixi.extras.AnimatedSprite(frames)

        // Setup the position of the bunny
        const randomX = Math.floor(Math.random() * 65 + 15) // 15-80
        const startX = this.app.renderer.width - randomX
        anim.x = startX
        anim.y = this.app.renderer.height - 80
        anim.height = 50
        anim.width = 50
        anim.anchor.set(0.5)
        anim.animationSpeed = 0.2
        anim.play()

        // Add the bunny to the scene we are building
        this.app.stage.addChild(anim)
        let moveReverse = true

        // Listen for frame updates
        this.app.ticker.add(() => {
          if (anim.y > this.app.renderer.height / 3) {
            anim.y -= 4
          } else {
            frames = []
            anim.stop()
            anim.destroy()
            this.app.stop()
            return
          }

          if (moveReverse) {
            anim.x += 0.5
          } else {
            anim.x -= 0.5
          }

          if (anim.x >= startX + 10) {
            moveReverse = false
          } else if (anim.x <= startX - 10) {
            moveReverse = true
          }
        })
      })
  }

  public componentWillUnmount() {
    this.app.stop()
  }

  /**
   * Simply render the div that will contain the Pixi Renderer.
   */
  public render() {
    const component = this
    return (
      <div
        ref={(thisDiv) => {
          if (thisDiv) {
            component.gameCanvas = thisDiv
          }
        }}
      />
    )
  }
}
