class Cart < ActiveRecord::Base
  has_many :item_in_carts, -> { order "created_at" }
  belongs_to :delivery_destination

  def self.find_or_create(anonymous_id, user_id)
    cart = nil
    ActiveRecord::Base.transaction do

      logged_in_user_cart = Cart.where(user_id: user_id).where(ordered: false).first
      anonymous_user_cart = Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first

      safe_user_id = (user_id > 0) ? user_id : nil
      if safe_user_id.nil?
        cart = anonymous_user_cart || Cart.create!(anonymous_id_string: anonymous_id, user_id: safe_user_id, ordered: false )
      else
        cart = logged_in_user_cart || Cart.create!(anonymous_id_string: nil, user_id: safe_user_id, ordered: false )
        logged_in_user_cart = cart
      end

      # add the contents of anonymous cart
      # to the logged in one on login
      if logged_in_user_cart and anonymous_user_cart
        logged_in_items = logged_in_user_cart.item_in_carts
        anonymous_user_cart.item_in_carts.each do |a_item|
          item_exists = false

          logged_in_items.each do |l_item|
            if a_item.item_id == l_item.item_id
              l_item.count += a_item.count
              l_item.save!
              a_item.destroy
              item_exists = true
              break
            end
          end

          unless item_exists
            a_item.cart_id = logged_in_user_cart.id
            a_item.save!
          end
        end

      end
      cart.delivery_destination ||= DeliveryDestination.create_from_last(anonymous_id, safe_user_id);
      cart.save!

    end
    return cart
  end

  def self.just_find(anonymous_id,user_id)
    cart = Cart.where(user_id: user_id).where(ordered: false).first
    cart ||= Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
    return cart
  end

  def confirmed_at
    delivery_destination.updated_at.in_time_zone('Europe/Sarajevo')
  end

  def delivery_cost
    place = Place.by_code_or_default(delivery_destination.place)
    if delivery_destination.instant_delivery
      place.instant_delivery_price
    else
      place.delivery_price
    end
  end

  def total
    sum = item_in_carts.inject (0) { |sum, iic| sum + (iic.price * iic.count) }
    sum += delivery_cost
  end

  def title
    number = id
    name = delivery_destination.name 
    value = Helper.money(total)
    phone = "0#{delivery_destination.phone}"
    "BR: #{number} za #{name} (#{phone}) - #{value}"
  end
end
