<template>
  <div ref="_djkr" :id="elId" :class="`chps3_mask ${snapped?'snapped':''}`">
    <canvas ref="_darkpanel">Does not support canvas</canvas>
  </div>
</template>
<script>
import { PolygonExPs3 } from "../engines/three/wrapengine/psx_generator"
import elementbase from "../mixins/tools/elementbase"
import {
  cancelAnimationFrameHandle,
  requestAnimationFrameHandle,
  windowAddEvent,
  windowRemoveEvent
} from "../engines/util/framehandle"

export default {
  name: "BgPs3",
  mixins: [elementbase],
  data() {
    return {
      polygons: [],
      t: 0,
      r_id: null,
      rep_pt: { x: 0, y: 0 },
      cutoff_d: 169,
      ctx2d: null,
      N_POLY: 32,
      r: {
        w: 0,
        h: 0
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.init()
      windowAddEvent("resize", this.init, false)
    })
  },
  beforeDestroy() {
    windowRemoveEvent("resize", this.init)
    cancelAnimationFrameHandle(this.r_id)
  },
  methods: {
    init() {
      const c = this.$refs._darkpanel
      c.addEventListener("mousemove", function (e) {
        this.rep_pt.x = e.clientX
        this.rep_pt.y = e.clientY
      }, false)

      this.ctx2d = c.getContext("2d")
      if (this.r_id) {
        cancelAnimationFrameHandle(this.r_id)
      }

      const maxx = window.innerWidth
      const maxy = window.innerHeight
      if (!this.snapped) {
        this.w = maxx
        this.h = maxy
      } else {
        this.setRefsParentDimension(this.$refs._djkr)
      }

      this.rep_pt.x = this.w / 2
      this.rep_pt.y = this.h / 2
      this.r.w = this.w
      this.r.h = this.h

      c.width = this.w

      c.height = this.h

      for (let i = 0; i < this.N_POLY; i++) {
        this.polygons.push(new PolygonExPs3())
        this.polygons[i].init(this.r)
      }

      this.draw()
    },
    draw() {
      let hue_diff
      this.ctx2d.clearRect(0, 0, this.r.w, this.r.h)
      for (let i = 0; i < this.N_POLY; i++) {
        this.polygons[i].move(this.polygons, this.rep_pt, this.N_POLY, this.r)
        this.polygons[i].draw(this.ctx2d)
        for (let j = 0; j < i; j++) {
          hue_diff = Math.abs(this.polygons[i].hue - this.polygons[j].hue)
          if (hue_diff < 32 || hue_diff > 328) {
            this.polygons[i].connectTo(this.ctx2d, this.polygons[j], this.cutoff_d, this.r)
          }
        }
      }
      this.t++
      this.r_id = requestAnimationFrameHandle(this.draw)
    }
  }
}
</script>
