class ApiShoppingCartsController < ApiController

  before_filter :api_any_user

  respond_to :json

  def log
    @log || Logging.logger[VanillaForumsController  ]
  end

  def index
    @carts = any_user.shopping_carts
  end

  def add_jamtrack
    jam_track = JamTrack.find_by_id(params[:id])

    # verify JamTrack exists
    if jam_track.nil?
      raise StateError, "Invalid JamTrack."
    end

    @cart = ShoppingCart.add_jam_track_to_cart(any_user, jam_track, params[:variant])

    if @cart.errors.any?
      response.status = :unprocessable_entity
      respond_with @cart
    else
      # let add_jamtrack.rabl take over
    end
  end

  def add_gift_card
    gift_card_type = nil

    id = params[:id]

    if id && id.to_i == 5
      gift_card_type = 'jam_tracks_5'
    elsif id && id.to_i == 10
      gift_card_type = 'jam_tracks_10'
    end

    gift_card = GiftCardType.find_by_id(gift_card_type)

    # verify GiftCard exists
    if gift_card.nil?
      raise StateError, "Invalid JamTrack."
    end

    @cart = ShoppingCart.add_item_to_cart(any_user, gift_card)

    if @cart.errors.any?
      response.status = :unprocessable_entity
      respond_with @cart
    else
      # let add_gift_card.rabl take over
    end
  end

  def update_cart
    @cart = ShoppingCart.find_by_id params[:id]

    #verify Cart exists
    raise StateError, "Invalid Cart." if @cart.nil?

    @cart.quantity = params[:quantity]

    if @cart.errors.any?
      response.statue = :unprocessable_entity
      respond_with @cart
    else
      # let update_cart.rabl take over
    end
  end

  def remove_cart
    @cart = any_user.shopping_carts.find_by_id(params[:id])
    raise StateError, "Invalid Cart." if @cart.nil?

    ShoppingCart.remove_jam_track_from_cart(any_user, @cart)

    # let remove_cart.rabl take over
  end

  # take all shopping carts from anonymous user and copy them to logged in user
  def port
    if current_user && anonymous_user
      ShoppingCart.port(current_user, anonymous_user)
    else
      render :json => {message: 'one or both users not available'}, :status => 403
    end
  end

  def clear_all
    any_user.destroy_all_shopping_carts
    render :json=>{}, :status=>200
  end

end
