require 'spec_helper'

describe ShoppingCart do

  let(:user) { FactoryGirl.create(:user) }
  let(:jam_track) {FactoryGirl.create(:jam_track) }
  let(:jam_track2) {FactoryGirl.create(:jam_track) }

  before(:each) do
    ShoppingCart.delete_all
  end

  it "can reference a shopping cart" do
    shopping_cart = ShoppingCart.create user, jam_track, 1

    ShoppingCart.count.should == 1
    user.shopping_carts.count.should == 1
    user.shopping_carts[0].product_info[:name].should == jam_track.name
    user.shopping_carts[0].product_info[:price].should == jam_track.price
    user.shopping_carts[0].cart_type.should == jam_track.class::PRODUCT_TYPE
    user.shopping_carts[0].quantity.should == 1
  end


  it "maintains only one fre JamTrack in ShoppingCart" do
    cart1 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
    cart1.should_not be_nil
    cart1.errors.any?.should be_false
    user.reload
    cart2 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
    cart2.errors.any?.should be_false
    user.reload
    user.shopping_carts.length.should eq(1)
    cart3 = ShoppingCart.add_jam_track_to_cart(user, jam_track2)
    cart3.errors.any?.should be_false
    user.reload
    user.shopping_carts.length.should eq(1)
  end

  it "should not add duplicate JamTrack to ShoppingCart" do
    user.has_redeemable_jamtrack = false
    user.save!
    cart1 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
    cart1.should_not be_nil
    cart1.errors.any?.should be_false
    user.reload
    cart2 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
    cart2.errors.any?.should be_true
  end

  describe "redeemable behavior" do

    it "removes redeemable item to shopping cart (maintains only one in cart)" do

      user.has_redeemable_jamtrack.should be_true
      cart1 = ShoppingCart.add_jam_track_to_cart(user, jam_track)
      cart1.should_not be_nil
      user.reload
      cart2 = ShoppingCart.add_jam_track_to_cart(user, jam_track2)
      cart2.should_not be_nil

      cart1.marked_for_redeem.should eq(1)
      cart2.marked_for_redeem.should eq(1)
      ShoppingCart.remove_jam_track_from_cart(user, jam_track)

      user.shopping_carts.length.should eq(0)
      cart2.reload
      cart2.marked_for_redeem.should eq(1)
    end
  end
end
