module HungrAuth
  class Users::PaymentMethodsController < HungrAuth::ApplicationController
    before_filter :authenticate_user!, :only => :create
    before_filter :verify_card_token, :only => :create

    def create
      current_user.customer? ? update_customer_card(params[:card_token]) : create_customer_with_card(params[:card_token])
      if current_user.reload.customer? && current_user.active_for_charge?
        render :status => :ok, :json => {:customer => current_user.customer?, :active => current_user.active_for_charge?} 
      else
        render :status => :bad_request, :json => {:customer => current_user.customer?, :active => current_user.active_for_charge?} 
      end
    end

    protected

    def verify_card_token
      unless params[:card_token]
        return render :status => :bad_request, :json => {}
      end
    end

    def update_customer_card(card_token)
      begin
        customer = Stripe::Customer.retrieve(current_user.customer_id)
        customer.card = card_token
        customer.save
        current_user.update_attributes({:has_active_card => true})
      rescue
        current_user.update_attributes({:customer_id => nil, :has_active_card => false})
      end
    end

    def create_customer_with_card(card_token)
      begin
        response = Stripe::Customer.create({:description => "User: #{current_user._id.to_s}", :card => card_token})
        current_user.update_attributes({:customer_id => response.id, :has_active_card => response.respond_to?(:active_card)})
      rescue
        current_user.update_attributes({:customer_id => nil, :has_active_card => false})
      end
    end

  end
end
