module AR::Game::NpcDialogBehavior 

  
  #...initialize them here
  def self.init ar_object 
    ar_object.class.attr_serializeable :root_dialog_node_class do |root_node, op, inst|
      case op
      when :load
        Object.const_get(root_node) unless root_node.nil? or root_node.empty?
      when :unload
        root_node.to_s
      end
    end
  end


  def self.extended ar_object
    self.init ar_object
    ar_object.resolutions << release_dialog_node_presented_on_dialog_began
    #add to object's event subscriptions and resolutions here...
  end 

  def self.release_dialog_node_presented_on_dialog_began
    AR::Events::Resolution.new event_class: AR::Events::DialogBeganEvent, as: "npc" do |e|
      npc = e.npc
      npc.create AR::Events::DialogNodeActivatedEvent, dialog_node: npc.root_dialog_node_class.new(npc), npc: npc
    end
  end


  class Node
    attr_accessor :limbs #other nodes
    attr_accessor :npc
    attr_accessor :player_speech_event
    attr_accessor :npc_speech_or_other_events
    def player_speaks text
      AR::Events::CharacterTalked.new character: player, speech: text
    end

    def npc_speaks text
      AR::Events::CharacterTalked.new character: npc, speech: text
    end

    def loop_to node
      AR::Events::DialogNodeActivatedEvent.new npc: npc, dialog_node: node
    end
    
    def initialize npc 
      self.npc = npc 
      self.limbs = []
      #subclass should initialize it's own nodes
    end

    def events
      ([player_speech_event] + [npc_speech_or_other_events]).flatten
    end

    def player
      self.npc.world.player
    end

  end

  class ExampleNode < Node
    def initialize npc 
      super
      limbs.push ExampleNode2.new npc 
      limbs.push ExampleNode2.new npc 
    end

    def player_speech_event
      npc.create AR::Events::CharacterTalked, character: player, speech: "Good day to you, sire"
    end
    def npc_speech_or_other_events 
      npc.create AR::Events::CharacterTalked, character: npc, speech: "I really don't want to talk right now..."
    end
  end

  class ExampleNode2 < Node
    def initialize character
      super
    end

    def player_speech_event
      npc.create AR::Events::CharacterTalked, character: player, speech: "Oh C'mon, you don't look THAT busy."
    end

    def npc_speech_or_other_events 
      npc.create AR::Events::CharacterTalked, character: npc, speech: "Well, I AM.  So get lost."
    end
    
  end




end
