module AuthForum
  class Cart < ActiveRecord::Base
    has_many :line_items, :dependent => :destroy

    def add_product(product_id, quantity = 1)
      current_item = line_items.find_by_product_id(product_id)
      if current_item.present?
        current_item.quantity += quantity.to_i
      else
        current_item = line_items.build(:product_id => product_id, :quantity => quantity)
      end
      current_item
    end

    def total_cart_item
      line_items.sum(:quantity)
    end

    def total_price
      line_items.collect { |item| item.quantity * item.product.price }.sum
    end

    def to_s
      id
    end

  end
end
