// tilemap2d.cm - Tilemap factory
//
// Creates tilemap data objects that register with film2d

var film2d = use('film2d')

var tilemap = {
  type: 'tilemap',
  
  at: function(pos) {
    var x = pos.x - this.offset_x
    var y = pos.y - this.offset_y
    if (!this.tiles[x]) return null
    return this.tiles[x][y]
  },
  
  set: function(pos, image) {
    var x = pos.x - this.offset_x
    var y = pos.y - this.offset_y
    
    while (this.tiles.length <= x)
      this.tiles.push([])

    while (this.tiles[x].length <= y)
      this.tiles[x].push(null)
    
    this.tiles[x][y] = image
  },

  clear: function() {
    this.tiles = []
  },
  
  destroy: function() {
    film2d.unregister(this._id)
  }
}

//stone(tilemap)

// Factory function - auto-registers with film2d
return function(props) {
  var defaults = {
    type: 'tilemap',
    tiles: [],
    offset_x: 0,
    offset_y: 0,
    plane: 'default',
    layer: 0,
    groups: [],
    tile_width: 1,
    tile_height: 1,
    opacity: 1,
    tint: {r: 1, g: 1, b: 1, a: 1}
  }
  
  var data = {}
  for(var k in defaults) data[k] = defaults[k]
  for(var k in props) data[k] = props[k]
  
  var newtilemap = meme(tilemap, data)
  film2d.register(newtilemap)
  return newtilemap
}
