class Tile
  constructor: ->
    @layers = []
    for restype, i in allResourceTypes()
      @layers.push new Tilelayer(
        type: restype,
        depth: i,
        amount: Math.round(Math.random(app.game.maxTileAmount-10)+10)
      )
    
    @currentLayer = 0
    @entity = null
    @isActive = false

  click: (button)->
    if button == "left"
      if @layers[@currentLayer].collect()
        name = app.layerIndexToName(@currentLayer)
        app.game.resources[name] += 1
      else
        @currentLayer += 1
        # If we reach the bottom, the entity on top dies.
        @entity = null if @currentLayer == allResourceTypes().length-1

  tick: ->
    @entity.tick @ if @entity

  moveIn: ->
    @isActive = true

  moveOut: ->
    @isActive = false

  select: ->
    @isSelected = true

  deselect: ->
    @isSelected = false

  getCurrentLayer: ->
    @layers[@currentLayer]

  render: (x, y)->
    tileLayer = @getCurrentLayer()
    app.layer.drawRegion app.images.layers, tileLayer.sprite, x*8, y*8

    if @entity
      app.layer.drawRegion app.images.entities, @entity.sprite(), x*8, y*8

    if (@entity and @entity.isMoveable()) or @isActive
      # Draw the status indicator.
      app.layer.drawImage app.images.progress, x*8, y*8
      numPercent = Math.floor((tileLayer.amount*6)/app.game.maxTileAmount)
      for i in [0..numPercent]
        color = ["#f00", "#a00", "#f60", "#aa0", "#0a0", "#0a0"][numPercent]
        color = ["#f00", "#f00", "#f80", "#ff0", "#0f0", "#0f0"][numPercent] if i == numPercent
        app.layer.setPixel(color, x*8+1+i, y*8+6)
    
    if @isActive
      app.layer.drawImage app.images.active, x*8, y*8

    if @isSelected    
      app.layer.drawImage app.images.selected, x*8, y*8


