module AR::Game::ActorBehavior 
  attr_accessor :last_action_this_tick
  attr_accessor :last_action
  
  #...initialize them here
  def self.init ar_object 
    ar_object.class.attr_serializeable :initiative, :action_points, :ownership
    ar_object.initiative = 0
    ar_object.register_gauge "action_points"
    ar_object.after_gauges_init do |obj|
      ap = obj.gauge "action_points"
      ap.change_current_and_max 3
    end
    ar_object.last_action = nil
    ar_object.last_action_this_tick = nil
    ar_object.ownership = "its"
  end


  def action_points
    gauge("action_points").modified_current
  end



  def self.extended ar_object
    self.init ar_object
    ar_object.subscriptions << self.attach_to_clock_tick(ar_object)
    ar_object.resolutions << self.release_gauges_changed_on_action_performed
  end 


  def self.attach_to_clock_tick ar_object
    AR::Events::Subscription.new event_class: AR::Events::ClockTickEvent do |e|

      #raise "Object #{ar_object} should not be here"   if ar_object.dead? 
      if ar_object.dead?

      else
        ar_object.last_action = nil
        ar_object.last_action_this_tick = nil
        ar_object.gauge("action_points").to_max!
        ar_object.initiative = rand(1..20) 
        dex = ar_object.gauge("dexterity")
        unless dex.nil?
          ar_object.initiative += dex.modified_current
        end

        e.actors << ar_object 
      end
    end
  end   

  def self.release_gauges_changed_on_action_performed
    AR::Events::Resolution.new event_class: AR::Events::ActionPerformedEvent, as: "performer" do |e|
      p = e.performer 
      a = e.action
      results = []
      g = p.gauge("action_points")
      results.push(AR::Events::GaugeChanged.new gauge: g, which: "current", amount: -a.ap_cost)

      g = p.gauge("hunger")
      unless g.nil?
        results.push(AR::Events::GaugeChanged.new gauge: g, gauge_owner: p, which: "current", amount: a.ap_cost)
      end
      results 
    end
  end

end
