class Game_System
  alias rb_initialize initialize
  def initialize
    @armor_storage = {}
    rb_initialize
  end
  def armor_storage(armor_id)
    @armor_storage = {} if @armor_storage.nil?
    return @armor_storage[armor_id].nil? ? 2 : @armor_storage[armor_id]
  end
  def storage_export(id, number)
    @armor_storage[id] = [armor_storage(id) - number, 0].max
  end
end
class Window_ArmorSelect < Window_Selectable
  def initialize
    super(0, 0, 256, 32)
    self.x = 320 - width / 2
    self.y = 240 - height / 2
    self.visible = false
    self.active = false
    self.index = 0
    refresh
  end
  def refresh
    @data = []
    (1..3).each do |i|
      id = $game_variables[i]
      armor = $data_armors[id]
      @data.push($data_armors[id]) unless armor.nil? || $game_system.armor_storage(id) == 0
    end
    self.height = (1 + @data.size) * 32
    if self.contents != nil
      self.contents.dispose
      self.contents = nil
    end
    @item_max = @data.size
    if @item_max > 0
      self.contents = Bitmap.new(width - 32, @item_max * 32)
      (0...@item_max).each do |i|
        draw_item(i)
      end
    end
  end
  def draw_item(index)
    item = @data[index]
    if item == nil
      return
    end
    x = 4
    y = 32 * index
    color = $game_system.armor_storage(item.id) > 0 ? normal_color : disabled_color
    self.contents.font.color = color
    opacity = $game_system.armor_storage(item.id) > 0 ? 255 : 128
    bitmap = RPG::Cache.icon(item.icon_name)
    self.contents.blt(x, y + 4, bitmap, Rect.new(0, 0, 24, 24), opacity)
    self.contents.draw_text(x + 28, y, 160, 32, item.name)
    text = ": " + $game_system.armor_storage(item.id).to_s
    self.contents.draw_text(0, y, width - 32, 32, text, 2)
  end
  def armor
    @data[self.index]
  end
  def show
    refresh
    self.visible = true
    self.active = true
  end
end
class Scene_Map
  alias rb_main main
  def main
    @armor_window = Window_ArmorSelect.new
    rb_main
    @armor_window.dispose
  end
  alias rb_update update
  def update
    if @armor_window.active
      update_armor
      return
    end
    rb_update
  end
  def update_armor
    @armor_window.update
    if Input.trigger?(Input::C)
      armor_id = @armor_window.armor.id
      if $game_system.armor_storage(armor_id) == 0
        $game_system.se_play($data_system.buzzer_se)
        return
      end
      $game_system.se_play($data_system.decision_se)
      @armor_window.active = false
      @armor_window.visible = false
      $game_party.gain_armor(armor_id, 1)
      $game_system.storage_export(armor_id, 1)
      return
    end
    if Input.trigger?(Input::B)
      $game_system.se_play($data_system.cancel_se)
      @armor_window.visible = false
      @armor_window.active = false
      return
    end
  end
  def show_armor_select
    @armor_window.show
  end
end