package com.stripe.example.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.stripe.android.CustomerSession;
import com.stripe.android.StripeError;
import com.stripe.android.model.Customer;
import com.stripe.android.model.PaymentMethod;
import com.stripe.android.view.PaymentMethodsActivity;
import com.stripe.android.view.PaymentMethodsActivityStarter;
import com.stripe.example.R;
import com.stripe.example.controller.ErrorDialogHandler;
import com.stripe.example.service.ExampleEphemeralKeyProvider;

/**
 * An example activity that handles working with a {@link CustomerSession}, allowing you to
 * add and select sources for the current customer.
 */
public class CustomerSessionActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_SELECT_SOURCE = 55;

    private Button mSelectSourceButton;
    private TextView mSelectedSourceTextView;
    private ProgressBar mProgressBar;
    private ErrorDialogHandler mErrorDialogHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_session);
        setTitle(R.string.customer_payment_data_example);
        mProgressBar = findViewById(R.id.customer_progress_bar);
        mSelectedSourceTextView = findViewById(R.id.tv_customer_default_source_acs);
        mSelectSourceButton = findViewById(R.id.btn_launch_payment_methods_acs);
        mSelectSourceButton.setEnabled(false);
        mErrorDialogHandler = new ErrorDialogHandler(this);
        CustomerSession.initCustomerSession(this,
                new ExampleEphemeralKeyProvider(
                        string -> {
                            if (string.startsWith("Error: ")) {
                                mErrorDialogHandler.show(string);
                            }
                        }));

        mProgressBar.setVisibility(View.VISIBLE);
        CustomerSession.getInstance().retrieveCurrentCustomer(
                new CustomerRetrievalListenerImpl(this));

        mSelectSourceButton.setOnClickListener(v -> launchWithCustomer());
    }

    private void launchWithCustomer() {
        new PaymentMethodsActivityStarter(this).startForResult(REQUEST_CODE_SELECT_SOURCE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_SELECT_SOURCE && resultCode == RESULT_OK) {
            final String selectedPaymentMethod =
                    data.getStringExtra(PaymentMethodsActivity.EXTRA_SELECTED_PAYMENT);
            final PaymentMethod paymentMethod = PaymentMethod.fromString(selectedPaymentMethod);

            if (paymentMethod != null && paymentMethod.card != null) {
                mSelectedSourceTextView.setText(buildCardString(paymentMethod.card));
            }
        }
    }

    @NonNull
    private String buildCardString(@NonNull PaymentMethod.Card data) {
        return data.brand + getString(R.string.ending_in) + data.last4;
    }

    private void onCustomerRetrieved() {
        mSelectSourceButton.setEnabled(true);
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    private void onRetrieveError(@Nullable String errorMessage) {
        mSelectSourceButton.setEnabled(false);
        mErrorDialogHandler.show(errorMessage);
        mProgressBar.setVisibility(View.INVISIBLE);
    }

    private static final class CustomerRetrievalListenerImpl
            extends CustomerSession.ActivityCustomerRetrievalListener<CustomerSessionActivity> {
        private CustomerRetrievalListenerImpl(@NonNull CustomerSessionActivity activity) {
            super(activity);
        }

        @Override
        public void onCustomerRetrieved(@NonNull Customer customer) {
            final CustomerSessionActivity activity = getActivity();
            if (activity != null) {
                activity.onCustomerRetrieved();
            }
        }

        @Override
        public void onError(int httpCode, @Nullable String errorMessage,
                            @Nullable StripeError stripeError) {
            final CustomerSessionActivity activity = getActivity();
            if (activity != null) {
                activity.onRetrieveError(errorMessage);
            }
        }
    }
}

@@ -786,16 +786,53 @@
 vider;%0A%0A
+import java.lang.ref.WeakReference;%0A%0A
 /**%0A * A
@@ -1954,230 +1954,38 @@
 der(
-%0A                        string -%3E %7B%0A                            if (string.startsWith(%22Error: %22)) %7B%0A                                mErrorDialogHandler.show(string);%0A                            %7D%0A                        %7D
+new ProgressListenerImpl(this)
 ));%0A
@@ -4474,11 +4474,693 @@
  %7D%0A    %7D
+%0A%0A    private static final class ProgressListenerImpl%0A            implements ExampleEphemeralKeyProvider.ProgressListener %7B%0A%0A        @NonNull private final WeakReference%3CCustomerSessionActivity%3E mActivityRef;%0A%0A        private ProgressListenerImpl(@NonNull CustomerSessionActivity activity) %7B%0A            this.mActivityRef = new WeakReference%3C%3E(activity);%0A        %7D%0A%0A        @Override%0A        public void onStringResponse(@NonNull String response) %7B%0A            final CustomerSessionActivity activity = mActivityRef.get();%0A            if (activity != null && response.startsWith(%22Error: %22)) %7B%0A                activity.mErrorDialogHandler.show(response);%0A            %7D%0A        %7D%0A    %7D
 %0A%7D%0A

Fix memory leak in CustomerSessionActivity (#960)