module AR
  module Game
    module Inhabitant 

      def self.init ar_object
        ar_object.class.attr_serializeable :parent_id
      end

      def self.extended ar_object
        init ar_object
        ar_object.resolutions.push clear_known_on_travel
        ar_object.resolutions.push remove_from_parent_on_removed_from_game
      end 

      def self.clear_known_on_travel
        AR::Events::Resolution.new event_class: AR::Events::ARObjectEnteredInhabitableEvent, as: "enterer" do |e|
          traveller = e.enterer
          gateway = e.gateway
          results = []
          if traveller.has_behavior? AR::Game::Perception
            traveller.known_objects.each do |o| 
              results.push(AR::Events::DiscoveryLostEvent.new perceiver: traveller, undiscovered: o)
            end
          end

          unless gateway.nil?
            gateway.parent.all_inhabitants.each do |o| 
              results.push(AR::Events::DiscoveryLostEvent.new perceiver: o, undiscovered: traveller)
            end
          end
          results
        end
      end


      def self.remove_from_parent_on_removed_from_game
        AR::Events::Resolution.new event_class: AR::Events::ObjectRemovedFromGame, as: "ar_object" do |e|
          obj  = e.ar_object

          obj.parent.remove_inhabitant obj unless obj.parent.nil?
          nil
        end
      end



      def placement
        return "" if parent.nil?
        parent.inhabitant_placement_for self
      end  

      def parent=(inhabitable)
        self.parent_id = (inhabitable.id rescue nil)
      end
      def parent
        world.find self.parent_id
      end

      #add more methods here

    end

  end
end
