module AR::Game::MemoryOfObjects


  #...initialize them here
  def self.init ar_object 
    ar_object.class.attr_serializeable :remembered_object_ids, :remembered_object_names_ids
    ar_object.remembered_object_ids = []
    ar_object.remembered_object_names_ids = []
  end

  def self.extended ar_object
    ar_object.add_behavior AR::Game::Perception
    self.init ar_object
    #add to object's event subscriptions and resolutions here...
    ar_object.resolutions << self.trigger_memory_on_discovered
    ar_object.resolutions << self.memorize_object
    ar_object.resolutions << self.memorize_object_name

  end 


  def self.memorize_object_name
    r = AR::Events::Resolution.new do |e|
      nameable = e.nameable
      memorizer = e.memorizer
      memorizer.remembered_object_names_ids.push  nameable.id
    end
    r.event_class = AR::Events::NameLearnedEvent
    r.as_who = "memorizer"
    r
  end

  def self.memorize_object
    r = AR::Events::Resolution.new do |e|
      discoverable= e.discoverable
      memorizer = e.memorizer
      memorizer.remembered_object_ids << discoverable.id
    end
    r.event_class = AR::Events::DiscoverableRememberedEvent
    r.as_who = "memorizer"
    r
  end

  def self.trigger_memory_on_discovered
    r = AR::Events::Resolution.new do |e|
      discovered = e.discovered
      perceiver = e.perceiver 
      ret = nil
      unless perceiver.has_known_about? discovered
        ret = e.engine.create AR::Events::DiscoverableRememberedEvent, ({memorizer: perceiver, discoverable: discovered})
      end
      ret
    end
    r.event_class = AR::Events::DiscoveryMadeEvent
    r.as_who = 'perceiver'
    r
  end

  def knows_name_of? ar_object
    remembered_object_names_ids.include? ar_object.id
  end

  def has_known_about? ar_object
    remembered_object_ids.include? ar_object.id
  end
end
