 _ = require "underscore"
 Glyph = require "../glyph/glyph"
+
+class ImagePool
+
+  constructor: () ->
+    @images = []
+
+  pop: () ->
+    img = @images.pop()
+    if img?
+      return img
+    else
+      return new Image()
+
+  push: (img) ->
+    if img.constructor == Array
+      Array::push.apply(@images, img)
+    else
+      @images.push(img)
 
 class ProjectionUtils
 

    return @url.replace("{X}", x).replace('{Y}', y).replace("{Z}", z)

class WMTSTileProvider extends MercatorTileProvider

  get_tile_meter_bounds: (x, y, z) ->
    [x, y, z] = @tms_to_wmts(x, y, z)
    return super(x, y, z)

  get_image_url: (x, y, z) ->
    [x, y, z] = @tms_to_wmts(x, y, z)

    return [minLon, minLat, maxLon, maxLat]

  get_tiles_by_extent: (extent, level) ->

    [xmin, ymin, xmax, ymax] = extent
    [txmin, tymin] = @meters_to_tile(xmin, ymin, level)
    [txmax, tymax] = @meters_to_tile(xmax, ymax, level)

    center_tile_x = (txmax - txmin) // 2
    center_tile_y = (tymax - tymin) // 2

    tiles = []
    for ty in [tymax..tymin] by -1
      for tx in [txmin..txmax] by 1
        tx = tx %% 2 ** level
        tiles.push([tx, ty, level, @get_tile_meter_bounds(tx, ty, level)])

    #TOOD: sort tiles by distance from center doesn't seem to be working
    tiles.sort (a, b) ->
      a_distance = Math.sqrt(Math.pow(center_tile_x - a[0], 2) + Math.pow(center_tile_y - a[1], 2))
      b_distance = Math.sqrt(Math.pow(center_tile_x - b[0], 2) + Math.pow(center_tile_y - b[1], 2))
      return a_distance - b_distance

    return tiles

