import { threeLayer } from './initScene3D'

function init(verticesArray, maxHeight) {
  let len = verticesArray.length

  for (let i = 0; i < len; i += 3) {
    verticesArray[i + 2] = maxHeight
  }
}

function singleAnimation (mesh, verticesArray, animateBuffArrays, stepTotal) {
  let len = verticesArray.length
  let pollIndex = 0;

  return function () {
    if (!mesh.visible) {
      pollIndex = stepTotal - 1
    }

    for (let i = 0, index = 0; i < len; i += 3, index++) {
      let Indexes = index * stepTotal + pollIndex
      verticesArray[i + 2] = animateBuffArrays[Indexes]
    }

    pollIndex++
    
    if (mesh.isRemove) {
      return true
    } else if (pollIndex < stepTotal) {
      mesh.geometry.attributes.position.needsUpdate = true;
      return false
    } else {
      return true
    }
  }
}


const animation = (() => {
  let taskStore = []
  let runing = false

  return function (...args) {
    taskStore.push(singleAnimation(...args))
    if (runing) return
    runing = true;

    function frame() {
      requestAnimationFrame(() => {
        for (let i = 0; i < taskStore.length; i++) {
          if (taskStore[i]()) {
            taskStore.splice(i, 1)
            i--
          }
        }
        threeLayer.renderScene()
        if (taskStore.length === 0) {
          runing = false
        } else {
          frame();
        }
      })
    }

    frame();
  }
})()


export {
  animation,
  init
}