import FeaturesToAttribute from '../worker/featuresToAttribute.worker'
import addMesh from '../business/addMesh'
import {threeLayer} from '../business/initScene3D'

let workers = [
  new FeaturesToAttribute()
]

workers.forEach(worker => {
  worker.addEventListener('message', event => {
    if (event.data.incident === 'addGeo') {
      addMesh(event)
    }
  })
})

let index = 0
function getWorker() {
  if (index >= workers.length) index = 0
  return workers[index++]
}


function addGeo(tiles) {
  let map = threeLayer.getMap()
  let setting = {
    center: map.getCenter(),
    maxNativeZoom: map.getMaxNativeZoom()
  }

  bus.emit('addGeoing')

  let length = workers.length
  let len = Math.floor(tiles.length / length)
  for (let i = 0; i < length; i++) {
    getWorker().postMessage(JSON.stringify({
      thing: 'getGeo',
      map: setting,
      tiles: tiles.slice(i * len, i === length - 1 ? tiles.length : len * (i + 1))
    }))
  }
}

function clearFids (fids) {
  getWorker().postMessage(JSON.stringify({
    thing: 'clearFids',
    fids: fids
  }))
}

export {
  addGeo,
  clearFids
}