module AR::Game::PaperDoll 
  
  #add attr_accessor properties here... 
  #if you don't need them serialized on save
  #
  def self.slots
    AR::Game::Equippable.slots
  end

  #...initialize them here
  def self.init ar_object 
    ar_object.class.attr_serializeable :paper_doll

    tmp = {}
    slots.each {|k, v| tmp[v] = nil }
    ar_object.paper_doll = tmp
  end

  def self.extended ar_object
    self.init ar_object
    ar_object.resolutions.push equip_on_event
    ar_object.resolutions.push unequip_on_event
    #add to object's event subscriptions and resolutions here...
  end 


  def self.equip_on_event
    AR::Events::Resolution.new event_class: AR::Events::ItemEquipped, as: "equipper" do |e|
      equipper = e.equipper
      item = e.item
      equipper.equip item
      AR::Events::ItemRemovedFromInventory.new item: item, inventory_owner: equipper
    end 
  end

  def self.unequip_on_event
    AR::Events::Resolution.new event_class: AR::Events::ItemUnequipped, as: "equipper" do |e|
      equipper = e.equipper
      item = e.item
      equipper.unequip item
      AR::Events::ItemAddedToInventory.new item: item, inventory_owner: equipper
    end 
  end


  def all_equipped_ids
    paper_doll.values.compact
  end

  def all_equipped_items
    all_equipped_ids.map{|id| world.find id}.compact
  end

  def equipped_on(slot)
    equipped_id = paper_doll[slot]
    world.find equipped_id
  end

  def unequip(item)
    raise "#{self.id} cant unequip non-equipped item #{item.id}" unless all_equipped_ids.include? item.id
    paper_doll[item.slot] = nil unless paper_doll[item.slot].nil?
    nil
  end

  def equip(item)
    if paper_doll.has_key? item.slot
      paper_doll[item.slot] = item.id 
    else
      raise "Cant equip item on slot: #{item.slot} #{item.slot.class}, which doesnt exist in keys: #{paper_doll.keys} types: (#{paper_doll.keys.map(&:class)}) "
    end
    nil
  end

end
