package com.SpinMoney.SpinMoney;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.paykun.sdk.PaykunApiCall;
import com.paykun.sdk.eventbus.Events;
import com.paykun.sdk.eventbus.GlobalBus;
import com.paykun.sdk.helper.PaykunHelper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.UUID;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;

public class PaykunActivity extends AppCompatActivity {

    private String amount;
    private String merchantIdLive;
    private String accessTokenLive;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paykun);
        getRazorPayKey();
        amount = getIntent().getExtras().getString("amnt");
        String orderID = "ODRNK" + UUID.randomUUID().toString().substring(0, 7);
        ((TextView) findViewById(R.id.orderid)).setText("order #" + orderID);
        ((TextView) findViewById(R.id.aaaa)).setText("INR " + amount);
        ((TextView) findViewById(R.id.licy)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Intent.ACTION_VIEW)
                        .setData(Uri.parse("https://paykun.com/privacy-policy")));
            }
        });
        ((Button) findViewById(R.id.pay)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startPayment();
            }
        });
    }

    private void getRazorPayKey() {
        ProgressDialog pd = new ProgressDialog(this);
        pd.setCancelable(false); pd.setMessage("wait.."); pd.show();
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=get_app_details";
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                    JSONObject objJson;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        objJson = jsonArray.getJSONObject(i);
                        merchantIdLive = objJson.getString("key");
                        accessTokenLive = objJson.getString("code");
                    }
                    pd.dismiss();
                } catch (Exception e) {
                    pd.dismiss();
                    makeText(PaykunActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                pd.dismiss();
                makeText(PaykunActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    public void startPayment() {
        JSONObject object = new JSONObject();
        try {
            object.put("merchant_id",merchantIdLive);
            object.put("access_token",accessTokenLive);
            object.put("customer_name",Utils.userName);
            object.put("customer_email",Utils.userEmail);
            object.put("customer_phone",Utils.userPhone);
            object.put("product_name","Refill Wallet");
            object.put("order_no",System.currentTimeMillis());
            object.put("amount",amount);
            object.put("isLive",true);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new PaykunApiCall.Builder(PaykunActivity.this).sendJsonObject(object);
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void getResults(Events.PaymentMessage message) {
        if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_SUCCESS)){
            int rest = Integer.parseInt(Utils.deposit) + Integer.parseInt(amount);
            addPointOnline(rest,Integer.parseInt(Utils.withdraw));
            makeText(this, "Payment Successful",LENGTH_SHORT).show();
        } else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_FAILED)){
            makeText(this, "Payment Failed",LENGTH_SHORT).show(); finish();
        } else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_SERVER_ISSUE)){
            Toast.makeText(PaykunActivity.this,PaykunHelper.MESSAGE_SERVER_ISSUE,Toast.LENGTH_SHORT).show();
        }else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_ACCESS_TOKEN_MISSING)){
            Toast.makeText(PaykunActivity.this,"Access Token missing",Toast.LENGTH_SHORT).show();
        } else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_MERCHANT_ID_MISSING)){
            Toast.makeText(PaykunActivity.this,"Merchant Id is missing",Toast.LENGTH_SHORT).show();
        } else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_INVALID_REQUEST)){
            Toast.makeText(PaykunActivity.this,"Invalid Request",Toast.LENGTH_SHORT).show();
        } else if(message.getResults().equalsIgnoreCase(PaykunHelper.MESSAGE_NETWORK_NOT_AVAILABLE)){
            Toast.makeText(PaykunActivity.this,"Network is not available",Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        GlobalBus.getBus().register(this);
    }
    @Override
    protected void onStop() {
        super.onStop();
        GlobalBus.getBus().unregister(this);
    }

    private void addPointOnline(int dm, int wm) {
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=update_wallet&user_id=" + Utils.userID + "&deposit=" + dm + "&withdraw=" + wm;
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(JSON_URL, null, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject objJson = jsonArray.getJSONObject(i);
                        String msg = objJson.getString("msg");
                        int status = objJson.getInt("success");
                        getProfile();
                        makeText(PaykunActivity.this, msg, LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    makeText(PaykunActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                makeText(PaykunActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    private void getProfile(){
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=user_profile&id=" + Utils.userID;
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject objJson = jsonArray.getJSONObject(i);
                        Utils.userID = objJson.getString("user_id");
                        Utils.userName = objJson.getString("name");
                        Utils.userEmail = objJson.getString("email");
                        Utils.userDP = objJson.getString("user_pro_image");
                        Utils.userPhone = objJson.getString("phone");
                        Utils.deposit = objJson.getString("deposit");
                        Utils.withdraw = objJson.getString("withdraw");
                    }
                    MainActivity.deposit.setText(getResources().getString(R.string.rupee).replace("0",Utils.deposit));
                    MainActivity.withdraw.setText(getResources().getString(R.string.rupee).replace("0",Utils.withdraw));
                    AddMoneyActivity.deposi.setText(getResources().getString(R.string.rupee).replace("0",Utils.deposit));
                    AddMoneyActivity.withdra.setText(getResources().getString(R.string.rupee).replace("0",Utils.withdraw));
                    finish();
                } catch (Exception e) {
                    makeText(PaykunActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                makeText(PaykunActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }


}