module Tiled
  class Map
    def draw(args, render_target = nil)
      raise ArgumentError.new(
        "Expected args value of type GTK::Args"
      ) if args.class != GTK::Args

      layers_to_draw = visible_layers()

      if render_target == nil
        # puts "Render target nil, sending map to outputs.primitives"
        primitives = args.outputs.primitives
      else
        # puts "We have a render target, sending map to outputs[#{render_target}].primitives"
        primitives = args.outputs[render_target].primitives
      end

      primitives << layers_to_draw.map do | layer |
        layer.sprites
      end
    end

    def visible_layers()
      visible_layers = []
      layers.map do | layer |
        visible_layers << layer if layer.visible
      end
      visible_layers
    end

    #gets the first object layer with the passed name of `layer_name`
    #then looks in that layer for the first object that has the name `object_name`
    #returns the 
    def object_by_name(layer_name, object_name)
      
      named_layer = @object_groups.reject do | layer |
        layer.name != layer_name
      end.first

      raise ObjectLayerNotFound, "The object layer \"#{layer_name}\" was not found in map \"#{@path}\"" if named_layer.nil?
      
      the_object = named_layer.objects.reject do | object |
        object.name != object_name
      end

      raise ObjectNameNotFound, "The object named \"#{object_name}\" was not found in object layer \"#{layer_name}\"" if the_object.empty?

      #if we get multiple objects with the name passed, only return the first item.
      the_object.first
    end
  end

  class ObjectLayerNotFound < Error; end
  class ObjectNameNotFound < Error; end

end