package com.friendvilla.bucksbuddy;

import static android.util.Base64.DEFAULT;
import static android.util.Base64.decode;
import static android.util.Base64.encode;
import static com.friendvilla.bucksbuddy.MainActivity.USER;
import static com.friendvilla.bucksbuddy.controls.Constant.GET_USER;
import static com.friendvilla.bucksbuddy.controls.Constant.POST_TXN;
import static com.friendvilla.bucksbuddy.controls.Constant.Tag;
import static com.friendvilla.bucksbuddy.controls.Constant.USER_ID;
import static com.friendvilla.bucksbuddy.controls.Constant.USER_REGISTER;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.friendvilla.bucksbuddy.controls.MessageBox;
import com.friendvilla.bucksbuddy.model.User;

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

import java.math.BigDecimal;

public class Method {

    public static boolean isConnected(Context ctx) {
        if(new String(Base64.decode(BuildConfig.PACKAGE,Base64.DEFAULT)).equals(BuildConfig.APPLICATION_ID)) {
            ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
            return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
        } else {
            return false;
        }
    }

    public static String formatedDate(String date) {
        String month = "";
        String[] sDate = date.split(" ");
        String[] splitDate = sDate[0].split("-");
        switch (splitDate[1]) {
            case "01":
            case "1":
                month = " Jan ";
                break;
            case "02":
            case "2":
                month = " Feb ";
                break;
            case "03":
            case "3":
                month = " Mar ";
                break;
            case "04":
            case "4":
                month = " Apr ";
                break;
            case "05":
            case "5":
                month = " May ";
                break;
            case "06":
            case "6":
                month = " Jun ";
                break;
            case "07":
            case "7":
                month = " Jul ";
                break;
            case "08":
            case "8":
                month = " Aug ";
                break;
            case "09":
            case "9":
                month = " Sep ";
                break;
            case "10":
                month = " Oct ";
                break;
            case "11":
                month = " Nov ";
                break;
            case "12":
                month = " Dec ";
                break;
        }
        return splitDate[2] + month + splitDate[0] + " " + sDate[1];
    }

    public static SpannableString title(Context ctx,String str,int end) {
        SpannableString spanString = new SpannableString(str.trim());
        spanString.setSpan(new ForegroundColorSpan(ctx.getResources().getColor(R.color.blue_01)),0,end,Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        spanString.setSpan(new ForegroundColorSpan(ctx.getResources().getColor(R.color.red_fd)),end,spanString.length(),Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        return  spanString;
    }

    public static JSONObject processTxn(Activity ctx,int status,String txn) {
        String BASE = new String(decode(BuildConfig.BASE_URL,DEFAULT));
        String txnData = USER_ID + "=" + status + "=" + txn;
        String HASH = new String(encode(txnData.getBytes(),DEFAULT));
        String URL = BASE + POST_TXN + HASH; final JSONObject[] obj = {null};
        Volley.newRequestQueue(ctx).add(new JsonObjectRequest(URL, response -> {
            try {
                JSONArray res = response.getJSONArray("result");
                obj[0] = res.getJSONObject(0);
            } catch (JSONException e) {
                MessageBox msg = new MessageBox(e.getMessage());
                msg.show(((AppCompatActivity)ctx).getSupportFragmentManager(),Tag);
            }
        }, error -> {
            MessageBox msg = new MessageBox(error.getMessage());
            msg.show(((AppCompatActivity)ctx).getSupportFragmentManager(),Tag);
        }));
        return obj[0];
    }

    public static void getUser(Activity ctx) {
        String BASE = new String(decode(BuildConfig.BASE_URL,DEFAULT));
        String HASH = new String(encode(USER_ID.getBytes(),DEFAULT));
        String URL = BASE + GET_USER + HASH;
        Volley.newRequestQueue(ctx).add(new JsonObjectRequest(URL,response -> {
            try {
                JSONArray res = response.getJSONArray("result");
                JSONObject obj = res.getJSONObject(0);
                if(obj.getString("success").equals("1")) {
                    JSONObject pro = obj.getJSONObject("profile");
                    String deposit = pro.getString("deposit");
                    String withdraw = pro.getString("withdraw");
                    String refercode = pro.getString("refercode");
                    String checkin = pro.getString("mobile");
                    String referby = pro.getString("referby");
                    USER.setValue(new User(deposit,withdraw,refercode,checkin,referby));
                }
            } catch (JSONException e) {
                MessageBox msg = new MessageBox(e.getMessage());
                msg.show(((AppCompatActivity)ctx).getSupportFragmentManager(),Tag);
            }
        }, error -> {
            MessageBox msg = new MessageBox(error.getMessage());
            msg.show(((AppCompatActivity)ctx).getSupportFragmentManager(),Tag);
        }));
    }

    public static JSONObject updateUser(Activity ctx,String d,String w, String win) {
        User user = USER.getValue(); assert user != null;
        BigDecimal wo = new BigDecimal(w).add(new BigDecimal(win));
        String BASE = new String(decode(BuildConfig.BASE_URL,DEFAULT));
        String userData = USER_ID + "@" + d + "@" + wo.toString() + "@" + user.getRefercode() + "@" + user.getReferby() + "@" + user.getCheckin();
        String HASH = new String(encode(userData.getBytes(),DEFAULT));
        String URL = BASE + USER_REGISTER + HASH; final JSONObject[] obj = {null};
        Volley.newRequestQueue(ctx).add(new JsonObjectRequest(URL, response -> {
            try {
                JSONArray res = response.getJSONArray("result");
                obj[0] = res.getJSONObject(0);getUser(ctx);
            } catch (JSONException e) {
                MessageBox msg = new MessageBox(e.getMessage());
                msg.show(((AppCompatActivity)ctx).getSupportFragmentManager(),Tag);
            }
        }, error -> {
            MessageBox msg = new MessageBox(error.getMessage());
            msg.show(((AppCompatActivity)ctx).getSupportFragmentManager(),Tag);
        }));
        return obj[0];
    }

    public static String[] calWallet(int betAmt) {
        User user = USER.getValue(); assert user != null;
        int DEPOSIT = new BigDecimal(user.getDeposit()).intValue();
        int WITHDRAW = new BigDecimal(user.getWithdraw()).intValue();
        BigDecimal restD = new BigDecimal(0),restW = new BigDecimal(0);
        int TOTAL = DEPOSIT + WITHDRAW;
        if(TOTAL >= betAmt) {
            if(DEPOSIT != 0) {
                if(DEPOSIT > betAmt) {
                    restD = new BigDecimal(user.getDeposit()).subtract(new BigDecimal(betAmt));
                    restW = new BigDecimal(user.getWithdraw());
                } else {
                    BigDecimal rest = new BigDecimal(betAmt).subtract(new BigDecimal(user.getDeposit()));
                    restW = new BigDecimal(user.getWithdraw()).subtract(rest);
                }
            } else {
                restW = new BigDecimal(user.getWithdraw()).subtract(new BigDecimal(betAmt));
            }
        }
        return new String[]{restD.toString(),restW.toString()};
    }

    public static double taxCal(int betAmt) {
        return ((double) betAmt / 100.0f) * 64;
    }
}
