import VoxelTexture from './voxeltexture'

const MISSING_UV = [[0.0, 1.0], [0.0, 0.0], [1.0, 0.0], [1.0, 1.0]]

const VoxelData = {
  index: 0,
  registeredVoxels: {},
  indexCache: [],
  texture: null,
  register: (name, def) => {
    def.index = VoxelData.index++
    VoxelData.registeredVoxels[name] = def
    VoxelData.indexCache.push(def)
    return def.index
  },
  get: (name) => {
    return VoxelData.registeredVoxels[name]
  },
  isSolid: (id) => {
    return VoxelData.indexCache[id] ? VoxelData.indexCache[id].solid : false
  },
  textureIndex: (id, face) => {
    const icache = VoxelData.indexCache[id]
    if (!icache.tiles) return MISSING_UV
    if (icache.tiles.length === 1) return VoxelTexture.faceUVs(icache.tiles[0])
    if (icache.tiles.length >= 2 && icache.tiles.length < 6) {
      // top face
      if (face === 1) {
        return VoxelTexture.faceUVs(icache.tiles[0])
      }
      return VoxelTexture.faceUVs(icache.tiles[1])
    }
    return VoxelTexture.faceUVs(icache.tiles[face]) || MISSING_UV
  }
}

export default VoxelData
