package com.makeeasy.dailyinterest;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.cashfree.pg.CFPaymentService.PARAM_APP_ID;
import static com.cashfree.pg.CFPaymentService.PARAM_CUSTOMER_EMAIL;
import static com.cashfree.pg.CFPaymentService.PARAM_CUSTOMER_NAME;
import static com.cashfree.pg.CFPaymentService.PARAM_CUSTOMER_PHONE;
import static com.cashfree.pg.CFPaymentService.PARAM_ORDER_AMOUNT;
import static com.cashfree.pg.CFPaymentService.PARAM_ORDER_CURRENCY;
import static com.cashfree.pg.CFPaymentService.PARAM_ORDER_ID;
import static com.cashfree.pg.CFPaymentService.PARAM_ORDER_NOTE;
import static com.makeeasy.dailyinterest.Constant.ARRAY_NAME;
import static com.makeeasy.dailyinterest.Constant.HOST_NAME;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.widget.TextView;

import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.cashfree.pg.CFPaymentService;
import com.google.android.material.navigation.NavigationView;

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

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

    public static String amount;
    private static String token,oId;
    @SuppressLint("StaticFieldLeak")
    public static TextView principle,interest,total;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        assert getSupportActionBar() != null;
        total = findViewById(R.id.bal);
        interest = findViewById(R.id.interest);
        principle = findViewById(R.id.principle);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        DrawerLayout drawer = findViewById(R.id.drawerlayout);
        NavigationView navigation = findViewById(R.id.nav_view);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this,drawer,toolbar,R.string.app_name,R.string.app_name);
        drawer.addDrawerListener(toggle); toggle.syncState();
        navigation.setNavigationItemSelectedListener(item -> {
            int id = item.getItemId();
            drawer.closeDrawer(GravityCompat.START);
            if (id == R.id.rate) {
                Uri ruri = Uri.parse("https://play.google.com/store/apps/details?id=" + getPackageName());
                Intent rate = new Intent(Intent.ACTION_VIEW,ruri);
                startActivity(rate);
            } else if (id == R.id.contact) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(getString(R.string.cnt))));
            } else if (id == R.id.policy) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(getString(R.string.ply))));
            }  else if (id == R.id.refund) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(getString(R.string.rfn))));
            }  else if (id == R.id.term) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(getString(R.string.tos))));
            } else if (id == R.id.about) {
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse(getString(R.string.abt))));
            } else if (id == R.id.share) {
                @SuppressLint("HardwareIds")
                String deviceID = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
                String referCode = deviceID.substring(0,6);
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT,"Share App");
                i.putExtra(Intent.EXTRA_TEXT,"Invest Money & get high return every day. Download the app now- https://dailyinterest.in\n\nUse this code- "+referCode+" to get Rs.10 rupees instant in your investment.");
                startActivity(Intent.createChooser(i,"Share By"));
            } else if (id == R.id.exit) {
                new AlertDialog.Builder(this)
                        .setMessage("Are you sure you want to exit?")
                        .setCancelable(false)
                        .setPositiveButton("Yes",(dialog,i) -> {
                            dialog.dismiss();
                            finish();
                        })
                        .setNegativeButton("No",(d,i) -> d.dismiss())
                        .show();
            }
            return true;
        });
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
        SimpleDateFormat dff = new SimpleDateFormat("dd MMM, yy",Locale.getDefault());
        String dt = df.format(Calendar.getInstance().getTime());String dtt = dff.format(Calendar.getInstance().getTime());
        ((TextView) findViewById(R.id.date)).setText("as on " + dtt);
        if(!Utils.getString(this,"bankinfo").equals("")) {
            ((TextView) findViewById(R.id.bank)).setText(Utils.getString(this,"bankinfo"));
        } else {
            if(!Utils.getString(this,"paytminfo").equals("")) {
                ((TextView) findViewById(R.id.bank)).setText(Utils.getString(this,"paytminfo"));
            } else {
                if(!Utils.getString(this,"upiinfo").equals("")) {
                    ((TextView) findViewById(R.id.bank)).setText(Utils.getString(this,"upiinfo"));
                } else {
                    ((TextView) findViewById(R.id.bank)).setText("(No A/c info found)");
                }
            }
        }
        if(!Utils.Rate.equals("")) {
            ((TextView) findViewById(R.id.rate)).setText("(" + Utils.Rate + "% Interest Monthly)");
        }
        if(Utils.userDP.equals(dt)) {
            BigDecimal bal = new BigDecimal(Utils.deposit).add(new BigDecimal(Utils.withdraw));
            principle.setText(Utils.deposit);interest.setText(Utils.withdraw);total.setText(bal.toString());
        } else {
            if(!Utils.userDP.equals("00/00/0000")) {
                try {
                    Date date1 = df.parse(dt);assert date1 != null;
                    Date date2 = df.parse(Utils.userDP);assert date2 != null;
                    long difference = Math.abs(date1.getTime() - date2.getTime());
                    long differenceDates = difference / (24 * 60 * 60 * 1000);
                    if(!Utils.deposit.equals("0") && !Long.toString(differenceDates).equals("0") ) {
                        BigDecimal s1 = new BigDecimal(Utils.deposit).multiply(new BigDecimal(Utils.Rate));
                        BigDecimal s2 = s1.divide(new BigDecimal("100"),2,RoundingMode.HALF_UP);
                        BigDecimal fi = s2.divide(new BigDecimal("30"),2,RoundingMode.HALF_UP);
                        BigDecimal ai = fi.multiply(new BigDecimal(Long.toString(differenceDates)));
                        BigDecimal wb = new BigDecimal(Utils.withdraw).add(ai);
                        addPointOnline(Utils.deposit,wb.toString());
                    }
                } catch (Exception exception) {
                    makeText(this, exception.getMessage(), LENGTH_SHORT).show();
                }
            } else {
                BigDecimal bal = new BigDecimal(Utils.deposit).add(new BigDecimal(Utils.withdraw));
                principle.setText(Utils.deposit);interest.setText(Utils.withdraw);total.setText(bal.toString());
            }
        }
        findViewById(R.id.addmoney).setOnClickListener(view -> {
            DepositBox depositBox = new DepositBox(this);
            depositBox.show(getSupportFragmentManager(),ARRAY_NAME);
        });
        findViewById(R.id.withdrawmoney).setOnClickListener(view -> {
            WithdrawBox withdrawBox = new WithdrawBox(this);
            withdrawBox.show(getSupportFragmentManager(),ARRAY_NAME);
        });
    }

    private void addPointOnline(String dm, String wm) {
        SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault());
        String dt = df.format(Calendar.getInstance().getTime());
        String JSON_URL = HOST_NAME + "api.php?method=update_wallet&user_id=" + Utils.userID + "&deposit=" + dm + "&withdraw=" + wm + "&date=" + dt;
        Volley.newRequestQueue(this).add(new JsonObjectRequest(JSON_URL, response -> {
            try {
                JSONArray jsonArray = response.getJSONArray(ARRAY_NAME);
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject objJson = jsonArray.getJSONObject(i);
                    String msg = objJson.getString("msg");
                    getProfile();
                    makeText(MainActivity.this, msg, LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                makeText(MainActivity.this,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> makeText(MainActivity.this,error.getMessage(),LENGTH_SHORT).show()));
    }

    @SuppressLint("SetTextI18n")
    private void getProfile(){
        String JSON_URL = HOST_NAME + "api.php?method=user_profile&id=" + Utils.getString(this,"UserId");
        Volley.newRequestQueue(this).add(new JsonObjectRequest(JSON_URL, response -> {
            try {
                JSONArray jsonArray = response.getJSONArray(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");
                }
                principle.setText(Utils.deposit);interest.setText(Utils.withdraw);
                BigDecimal bal = new BigDecimal(Utils.deposit).add(new BigDecimal(Utils.withdraw));
                total.setText(bal.toString());
            } catch (Exception e) {
                makeText(MainActivity.this,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> makeText(MainActivity.this,error.getMessage(),LENGTH_SHORT).show()));
    }

    public static void generateToken(Activity ctx,boolean upi) {
        ProgressDialog pd = new ProgressDialog(ctx);oId = "order" + new Random().nextInt();
        pd.setCancelable(false); pd.setMessage("wait.."); pd.show();
        String jURL = HOST_NAME + "tken.php?amt=" + amount + "&odr=" + oId;
        Volley.newRequestQueue(ctx).add(new JsonObjectRequest(jURL, jsonObject -> {
            try {
                token = jsonObject.getString("cftoken");
                CFPaymentService cfPaymentService = CFPaymentService.getCFPaymentServiceInstance();
                cfPaymentService.setOrientation(0);pd.dismiss();
                if(upi) {
                    cfPaymentService.upiPayment(ctx,myParams(),token,"PROD");
                } else {
                    cfPaymentService.doPayment(ctx,myParams(),token,"PROD","#3700B3","#FFFFFF",false);
                }
            } catch (JSONException e) {
                pd.dismiss();
                makeText(ctx,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> {
            pd.dismiss();
            makeText(ctx,error.getMessage(),LENGTH_SHORT).show();
        }));
    }

    private static Map<String, String> myParams() {
        Map<String, String> params = new HashMap<>();
        params.put(PARAM_APP_ID,Utils.CashFreeId);
        params.put(PARAM_ORDER_ID,oId);
        params.put(PARAM_ORDER_AMOUNT,amount);
        params.put(PARAM_ORDER_NOTE,"Add Money");
        params.put(PARAM_CUSTOMER_NAME,Utils.userName);
        if(Utils.userPhone.equals("") || Utils.userPhone.equalsIgnoreCase("null")) {
            params.put(PARAM_CUSTOMER_PHONE,"8906368080");
        } else {
            params.put(PARAM_CUSTOMER_PHONE,Utils.userPhone);
        }
        params.put(PARAM_CUSTOMER_EMAIL,Utils.userEmail);
        params.put(PARAM_ORDER_CURRENCY,"INR");
        return params;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            Bundle bundle = data.getExtras();
            if (bundle != null) {
                if (bundle.getString("txStatus") != null) {
                    if (bundle.getString("txStatus").equalsIgnoreCase("SUCCESS")) {
                        BigDecimal dm = new BigDecimal(Utils.deposit).add(new BigDecimal(amount));
                        addPointOnline(dm.toString(),Utils.withdraw);
                    } else {
                        makeText(this,bundle.getString("txStatus"),LENGTH_SHORT).show();
                    }
                } else {
                    makeText(this,"Error Response",LENGTH_SHORT).show();
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setMessage("Are you sure you want to exit?")
                .setCancelable(false)
                .setPositiveButton("Yes",(dialog,i) -> {
                    dialog.dismiss();
                    finish();
                })
                .setNegativeButton("No",(d,i) -> d.dismiss())
                .show();
    }
}