module AR::Game::Dexterity 
  EXP_THRESHOLDS = [3, 10, 20, 33, 49, 66, 84, 101, 118]
  
  #add attr_accessor properties here... 
  #if you don't need them serialized on save

  #...initialize them here
  def self.init ar_object 
    ar_object.register_gauge "dexterity"
    ar_object.register_gauge "avoidance"
    ar_object.register_gauge "accuracy"
    ar_object.after_gauges_init do |obj|
    dex = obj.gauge("dexterity")
      av = obj.gauge("avoidance")
      acc = obj.gauge("accuracy")
      dex.parents! av, with: AR::Game::GaugeBehavior::LinearGaugeRelation, data: {factor: 1}
      dex.parents! acc, with: AR::Game::GaugeBehavior::LinearGaugeRelation, data: {factor: 2}
      dex.change_current_and_max 1
      dex.manual_child_sync
    end

    ar_object.class.attr_serializeable :dexterity_exp
    ar_object.dexterity_exp = 0
  end

  def dexterity_lvl
    gauge("dexterity").modified_current
  end

  def supposed_dexterity_lvl
    currently = self.dexterity_lvl 
    lvl = currently
    EXP_THRESHOLDS.each_with_index do |threshold, i|
      lvl = i+1
      if dexterity_exp >= threshold
        next
      else
        break
      end
    end
    lvl
  end


  def self.add_dexterity_exp_on_hit_with_dagger
    AR::Events::Resolution.new event_class: AR::Events::HitSuccess, as: "hitter" do |e|
      c = e.hitter
      wep = c.equipped_on(:main_hand)
      if wep.class.to_s.include? "Dagger"
        c.dexterity_exp += 2
        c.strength_exp += 1
        AR.log("#{c.tag} is gaining 2/1 exp point in dexterity/strength, supposed lvl: #{c.supposed_dexterity_lvl}")
      end
      
      nil
    end
  end

  def self.gain_dexterity_lvl_on_slept
    AR::Events::Resolution.new event_class: AR::Events::CharacterSlept, as: "rester" do |e|
      c = e.rester
      currently = c.dexterity_lvl
      supposed = c.supposed_dexterity_lvl
      delta = supposed - currently
      if delta > 0
        AR::Events::ExpLevelGained.new leveler: c, gauge: c.gauge("dexterity"), amount: delta
      end
    end
  end



  def self.add_dexterity_exp_on_dodge
    AR::Events::Resolution.new event_class: AR::Events::ActionPerformedEvent, as: "performer" do |e|
      c = e.performer
      a = e.action
      if a.class==AR::Game::DefendAction
        tech = a.parameter("technique").argument
        if tech.class == AR::Game::DodgeTech
          c.dexterity_exp += 2 
          AR.log("#{c.tag} is gaining 2 exp point in dexterity from dodging, supposed lvl: #{c.supposed_dexterity_lvl}")
        end
      end
      nil
    end
  end




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


  #add more methods here

end
