package com.pixelnx.sam.jobportal.payment.paypal;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Window;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.paypal.android.sdk.payments.PayPalConfiguration;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;
import com.pixelnx.sam.jobportal.DTO.CommonDTO;
import com.pixelnx.sam.jobportal.LoginActivity;
import com.pixelnx.sam.jobportal.R;
import com.pixelnx.sam.jobportal.utils.AppConstans;
import com.pixelnx.sam.jobportal.utils.CustomTextHeader;
import com.pixelnx.sam.jobportal.utils.ProjectUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class PayPalActivity extends AppCompatActivity {

    //Payment Amount
    private String paymentAmount = "", email = "",plan_ID="";
    String paymentDetails="";
    private PayPalPayment payPalPayment;

    public static final int PAYPAL_REQUEST_CODE = 123;

    private static PayPalConfiguration config = new PayPalConfiguration()
            // Start with mock environment.  When ready, switch to sandbox (ENVIRONMENT_SANDBOX)
           // or For  live use this (ENVIRONMENT_PRODUCTION)//please past "ENVIRONMENT_PRODUCTION" in the place of "ENVIRONMENT_SANDBOX"
            .environment(PayPalConfiguration.ENVIRONMENT_SANDBOX)
            .clientId(PayPalConfig.PAYPAL_CLIENT_ID);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.paypal_activity);
        if (getIntent().hasExtra(AppConstans.AMOUNT) && getIntent().hasExtra(AppConstans.EMAIL)) {
            paymentAmount = getIntent().getStringExtra(AppConstans.AMOUNT);
            email = getIntent().getStringExtra(AppConstans.EMAIL);
            plan_ID = getIntent().getStringExtra(AppConstans.PLAN_ID);
            getPayment();
        }
    }

    private void getPayment() {

        //Getting the amount from editText
        //Creating a paypalpayment
        PayPalPayment payment = new PayPalPayment(new BigDecimal(paymentAmount), "USD", "to"+config,
                PayPalPayment.PAYMENT_INTENT_SALE);

        //Creating Paypal Payment activity intent
        Intent intent = new Intent(this, PaymentActivity.class);

        //putting the paypal configuration to the intent
        intent.putExtra(PayPalService.EXTRA_PAYPAL_CONFIGURATION, config);

        //Puting paypal payment to the intent
        intent.putExtra(PaymentActivity.EXTRA_PAYMENT, payment);

        //Starting the intent activity for result
        //the request code will be used on the method onActivityResult
        startActivityForResult(intent, PAYPAL_REQUEST_CODE);
    }

    @Override
    public void onDestroy() {
        stopService(new Intent(this, PayPalService.class));
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //If the result is from paypal
        if (requestCode == PAYPAL_REQUEST_CODE) {

            //If the result is OK i.e. user has not canceled the payment
            if (resultCode == Activity.RESULT_OK) {
                //Getting the payment confirmation
                PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
                //if confirmation is not null
                if (confirm != null) {
                    try {
                        //Getting the payment details
                         paymentDetails = confirm.toJSONObject().toString(4);
                        Log.i(" PAY", paymentDetails);

                        //Starting a new activity for the payment details and also putting the payment details with intent
                    /*    startActivity(new Intent(this, ConfirmationActivity.class)
                                .putExtra("PaymentDetails", paymentDetails)
                                .putExtra("PaymentAmount", paymentAmount));*/

                        JSONObject jsonDetails = new JSONObject(paymentDetails);
                        JSONObject res = jsonDetails.getJSONObject("response");

                        if (res.getString("state").equalsIgnoreCase("approved")) {
                            sendResponseToServer();
                        }
                        final Dialog dialog = new Dialog(PayPalActivity.this);

                        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                        dialog.setCancelable(true);
                        dialog.setTitle("Payment Option");
                        dialog.setContentView(R.layout.dialog_paypal);

                        CustomTextHeader tvPaypalResult = (CustomTextHeader) dialog.findViewById(R.id.tvPaypalResult);
                        tvPaypalResult.setText(paymentDetails.toString());

                        dialog.show();
                    } catch (JSONException e) {
                        Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
                    }
                }
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Log.i("paymentExample", "The user canceled.");
            } else if (resultCode == PaymentActivity.RESULT_EXTRAS_INVALID) {
                Log.i("paymentExample", "An invalid Payment or PayPalConfiguration was submitted. Please see the docs.");
            }
        }
    }


    public void sendResponseToServer() {
        ProjectUtils.showProgressDialog(PayPalActivity.this, false, "Please wait...");
        StringRequest stringRequest = new StringRequest(Request.Method.POST, AppConstans.BASE_URL + AppConstans.PAYPAL_SUCCESS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        ProjectUtils.pauseProgressDialog();
                        Log.e("TAG", "response:" + response);

                        CommonDTO commonDTO = new CommonDTO();
                        commonDTO = new Gson().fromJson(response, CommonDTO.class);
                        if (commonDTO.getStaus().equalsIgnoreCase("true")) {
                  //         startActivity(new Intent(PayPalActivity.this, LoginActivity.class));
                                    finish();
                        } else {
                            ProjectUtils.showToast(PayPalActivity.this, commonDTO.getMessage());
                        }

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        ProjectUtils.pauseProgressDialog();
                        Log.e("error_requter", error.toString());
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put(AppConstans.EMAIL, email);
                params.put(AppConstans.P_ID, plan_ID);
                return params;
            }
        };
        RequestQueue requestQueue = Volley.newRequestQueue(PayPalActivity.this);
        requestQueue.add(stringRequest);
    }
}



