require 'spec_helper'



describe ApiShoppingCartsController, type: :controller do

  render_views

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

  before(:each) do
    ShoppingCart.delete_all
    controller.anonymous_user.should be_nil
    controller.current_user.should be_nil
  end

  describe "logged in" do

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

    before(:each) do
      controller.current_user = user
      controller.anonymous_user = nil
    end

    it "add_jamtrack" do
      post :add_jamtrack, {:format => 'json', id: jam_track.id}
      response.status.should == 200
    end

    it "index" do
      cart = ShoppingCart.create(user, jam_track)
      cart.errors.any?.should be false
      user.reload
      user.shopping_carts.count.should eq(1)

      get :index, {:format => 'json'}
      response.status.should == 200
      response_body = JSON.parse(response.body)
      response_body.length.should eq(1)
      response_body[0]["id"].should eq(cart.id)
    end

    it "remove_cart" do
      cart = ShoppingCart.create(user, jam_track)
      delete :remove_cart, {:format => 'json', id: cart.id}
      response.status.should == 200
      ShoppingCart.find_by_id(cart.id).should be_nil
    end

    it "clears cart" do
      cart = ShoppingCart.create(user, jam_track)
      delete :clear_all, {:format => 'json'}
      response.status.should == 200
      ShoppingCart.find_by_id(cart.id).should be_nil
    end
  end

  describe "anonymous" do

    let(:user) { AnonymousUser.new('abc', {}) }

    before(:each) do
      controller.current_user = nil
      controller.anonymous_user = user
    end

    it "add_jamtrack" do
      post :add_jamtrack, {:format => 'json', id: jam_track.id}
      response.status.should == 200
      user.reload
      user.shopping_carts.count.should eql(1)
    end

    it "index" do
      cart = ShoppingCart.create(user, jam_track)

      get :index, {:format => 'json'}
      response.status.should == 200
      response_body = JSON.parse(response.body)
      response_body.length.should eq(1)
      response_body[0]["id"].should eq(cart.id)
    end

    it "remove_cart" do
      cart = ShoppingCart.create(user, jam_track)
      delete :remove_cart, {:format => 'json', id: cart.id}
      response.status.should == 200
      ShoppingCart.find_by_id(cart.id).should be_nil
    end

    it "clears cart" do
      cart = ShoppingCart.create(user, jam_track)
      delete :clear_all, {:format => 'json'}
      response.status.should == 200
      ShoppingCart.find_by_id(cart.id).should be_nil
    end
  end

  describe "cookieless" do

  end

end
