app.game =
  start: ->
    for i in [0..20*15-1]
      @map[i] = new Tile
    @map[20*5+10].entity = new Base
    
    @currentHoveredTile = new Tile
    @currentSelectedTile = null

    # Start the game tick
    window.setInterval @tick, 1000

    @hud.start()

  render: ->
    for tile, i in @map
      y = Math.floor(i/20)
      x = i-(y*20)
      tile.render(x, y)

    @hud.render()

  mousedown: (event)->
    tile = posToTile(event.x, event.y)
    tile.click(event.button)

    @currentSelectedTile.deselect() if @currentSelectedTile
    tile.select()
    @currentSelectedTile = tile

  mousemove: (event)->
    tile = posToTile(event.x, event.y)

    if tile
      if tile != @currentHoveredTile
        tile.moveIn()
        @currentHoveredTile.moveOut()
        @currentHoveredTile = tile

  keyup: (event) ->
    switch event.key
      when "m" then @createMiner()
      when "s" then @createSilo()
      when "c" then @cheatah()
      when "space"
        @currentSelectedTile.deselect() if @currentSelectedTile
        @currentSelectedTile = null

  tick: =>
    tile.tick() for tile in app.game.map

  createMiner: ->
    if @currentSelectedTile and @checkResource 'lubinit', 30, true
      @currentSelectedTile.entity = new Miner

  createSilo: ->
    if @currentSelectedTile and @checkResource 'oxodum', 20, true
      @currentSelectedTile.entity = new Silo

  checkResource: (type, amount, drain = false) ->
    if @resources[type] >= amount
      @resources[type] -= amount if drain
      return true
    false

  cheatah: ->
    for type, amount of @resources
      @resources[type] = 100

  map: []
  miners: []
  maxTileAmount: 15

  availableSiloStorage: ->
    space = 50
    for tile in app.game.map
      space += tile.spaceProvided if tile.spaceProvided
    space

  usedSiloStorage: ->
    space = 0
    space += amount for resource, amount of @resources
    space

  resources:
    stardust: 0
    dirt: 0
    bedrock: 0
    oxodum: 0
    lubinit: 0
    darkana: 0
    bio: 0
    notch: 0
    lava: 0
