summaryrefslogtreecommitdiff
path: root/app/controllers/characters/items_controller.rb
blob: 722c8ff2b7f4c587041d0546789276706f497412 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
class Characters::ItemsController < ApplicationController
  def index
    @character = Character.find(params[:character_id])
  end

  def equip
    @item = Item.find(params[:item_id])
    current_char.equip(@item)
    flash[:notice] = "Equipped #{@item.name}."
  rescue EquipmentError
    flash[:alert] = "Couldn't equip #{@item.name}."
  ensure
    redirect_to character_items_path(current_char)
  end

  def unequip
    current_char.unequip(params[:slot].to_sym)
    flash[:notice] = "Unequipped item."
  rescue EquipmentError
    flash[:alert] = "Couldn't unequip item."
  ensure
    redirect_to character_items_path(current_char)
  end

  def use
    @item = Item.find(params[:item_id])
    unless @item.usable?
      flash[:alert] = "You can't use #{@item.name}."
      redirect_to character_items_path(current_char) and return
    end
    unless current_char.character_items.exists?(item: @item)
      flash[:alert] = "You don't have #{@item.name}."
      redirect_to character_items_path(current_char) and return
    end
    @item.whatnot[:use_effects]&.each do |effect|
      case effect[:type]
      when "change_wounds"
        # This is basically duplicated in HearthAmenityController
        Character.transaction do
          wounds_change = [effect[:value], -current_char.wounds].max
          current_char.shift_item(@item, -1)
          current_char.wounds = current_char.wounds + wounds_change
          current_char.save!
          flash[:notice] = "#{effect[:message]}"
          heal_or_gain = wounds_change.positive? ? "gain" : "heal"
          flash[:notice] += " You #{heal_or_gain} #{wounds_change.abs} wound(s)."
        end
      when "activity"
        start_activity(Activity.find_by_gid(effect[:gid])) and return
      when "condition"
        condition = Condition.find_by_gid(effect[:gid])
        Character.transaction do
          current_char.shift_item(@item, -1)
          current_char.states.create!(condition: condition, expires_at: Time.now + effect[:duration])
          flash[:notice] = "#{effect[:message]}"
          flash[:notice] += " You gain the #{condition.name} condition."
        end
      else
        raise "Invalid use effect type string (#{effect[:type]})"
      end
      redirect_to character_items_path(current_char)
    end
  end
end