class ApiPayPalController < ApiController

  before_filter :api_signed_in_user

  respond_to :json


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

  def start_checkout
    cancel_path = params[:path] ? params[:path] : ERB::Util.url_encode('/client#/checkoutPayment')

    tax = true
    tax_rate = tax ? 0.0825 : 0
    total = current_user.shopping_cart_total.round(2)
    tax_total = (total * tax_rate).round(2)
    total = total + tax_total
    total = total.round(2)


    @api = PayPal::SDK::Merchant::API.new
    @set_express_checkout = @api.build_set_express_checkout(
        {
            :Version => "117.0",
            :SetExpressCheckoutRequestDetails =>
                {
                    :ReturnURL => ApplicationHelper.base_uri(request) + '/auth/paypal/checkout',
                    :CancelURL => ApplicationHelper.base_uri(request) + '/auth/paypal/checkout?cancel=1&path=' + cancel_path,
                  #  :NoShipping => "1",
                  #  :ReqConfirmShipping => "0",
                  #  :ReqBillingAddress => "1",
                    :PaymentDetails =>
                        [
                            {
                                :OrderTotal => {
                                    :currencyID => "USD",
                                    :value => total
                                },
                                :PaymentAction => "Sale"
                            }
                        ]
                }
        }
    )
    @set_express_checkout_response = @api.set_express_checkout(@set_express_checkout)

    log.info("User #{current_user.email}, SetExpressCheckout #{@set_express_checkout_response.inspect}")

    if @set_express_checkout_response.Ack == 'Failure'
      render json: {message: @set_express_checkout_response.Errors[0].LongMessage}, status: 422
      return
    end

    redirect_to Rails.configuration.paypal_express_url + '&token=' + ERB::Util.url_encode(@set_express_checkout_response.Token)
  end

  # called by frontend after the user comes back from initial express page
  def checkout_detail
    # here we can see if they will pay tax

    if !current_user.has_paypal_auth?
      render json: {}, :status => 404
      return
    end
    paypal_auth = current_user.paypal_auth

    @api = PayPal::SDK::Merchant::API.new
    @get_express_checkout_details = @api.build_get_express_checkout_details({:Token => paypal_auth.token})
    @response = @api.get_express_checkout_details(@get_express_checkout_details)

    puts @response.inspect
    tax = false
    if @response.Ack == 'Success'
      payerInfo = @response.GetExpressCheckoutDetailsResponseDetails.PayerInfo
      if payerInfo.Address && ( payerInfo.Address.Country == 'US' && payerInfo.Address.StateOrProvince == 'TX')
        # we need to ask for taxes
        tax = true
      end
    else
      render json: {message: @response.Errors[0].LongMessage}, status: 422
      return
    end

    log.debug("User #{current_user.email}, GetExpressCheckout: #{@get_express_checkout_details_response.inspect}")

    render json: {tax: tax}
  end

  # called by frontend when the user selects finally 'confirm purchase' (PLACE ORDER btn)
  def confirm_purchase
    if !current_user.has_paypal_auth?
      render json: {}, :status => 404
      return
    end

    error = nil
    response = {jam_tracks: [], gift_cards: []}

    #if Sale.is_mixed(current_user.shopping_carts)
    #  msg = "has free and non-free items. Try removing non-free items."
    #  render json: {message: "Cart " + msg, errors: {cart: [msg]}}, :status => 404
    #  return
    #end

    begin
      sales = Sale.place_order(current_user, current_user.shopping_carts, true)
    rescue RecurlyClientError => e
      render json: {message: e.errors[:message]}, :status => 422
      return
    rescue PayPalClientError => x
      render json: {message: x.errors[:message]}, :status => 422
      return
    end


    sales.each do |sale|
      sale.sale_line_items.each do |line_item|
        if line_item.is_jam_track?
          jam_track = line_item.product
          jam_track_right = jam_track.right_for_user(current_user)
          response[:jam_tracks] << {name: jam_track.name, id: jam_track.id, jam_track_right_id: jam_track_right.id, version: jam_track.version}
        elsif line_item.is_gift_card?
          gift_card = line_item.product
          response[:gift_cards] << {name: gift_card.name, id: gift_card.id}
        else
          raise 'unknown sale line item type: ' + line_item.product_type
        end
      end
    end

    set_purchased_jamtrack_cookie
    render :json => response, :status => 200
  end
end