package com.friendvilla.bucksbuddy;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static com.friendvilla.bucksbuddy.MainActivity.USER;
import static com.friendvilla.bucksbuddy.Method.calWallet;
import static com.friendvilla.bucksbuddy.Method.taxCal;
import static com.friendvilla.bucksbuddy.Method.title;
import static com.friendvilla.bucksbuddy.Method.updateUser;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.airbnb.lottie.LottieAnimationView;
import com.friendvilla.bucksbuddy.adapter.AmountAdapter;
import com.friendvilla.bucksbuddy.adapter.BetAdapter;
import com.friendvilla.bucksbuddy.model.Jackpot;
import com.friendvilla.bucksbuddy.model.User;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SlotActivity extends AppCompatActivity {

    private Handler handlr;
    private Runnable runable;
    private boolean isShow = false;
    private LottieAnimationView anim;
    private RecyclerView betView,amtView;
    public static int Nmbr = 0,Amnt = 0;
    private RecyclerView rv1,rv2,rv3,rv4,rv5;
    private List<Jackpot> finalList = new ArrayList<>();
    private MediaPlayer winMediaPlayer,slotMediaPlayer,looseMediaPlayer;

    @SuppressLint({"SetJavaScriptEnabled", "SetTextI18n"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_slot); anim = findViewById(R.id.win);
        ((TextView)findViewById(R.id.tvTitle)).setText(title(this,getString(R.string.jackpot_slots),7));
        findViewById(R.id.bal).setOnClickListener(view -> startActivity(new Intent(this,WalletActivity.class)));
        User user = USER.getValue(); assert user != null;
        BigDecimal bal = new BigDecimal(user.getDeposit()).add(new BigDecimal(user.getWithdraw()));
        ((TextView)findViewById(R.id.tvBal)).setText("₹ " + bal);
        rv1 = findViewById(R.id.rv1);rv2 = findViewById(R.id.rv2);rv3 = findViewById(R.id.rv3);
        rv4 = findViewById(R.id.rv4);rv5 = findViewById(R.id.rv5);handlr = new Handler();
        rv1.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rv2.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rv3.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rv4.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        rv5.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false));
        winMediaPlayer = MediaPlayer.create(this,R.raw.win);
        looseMediaPlayer = MediaPlayer.create(this,R.raw.wrong);
        findViewById(R.id.start).setOnClickListener(view -> {
            int DEPOSIT = new BigDecimal(user.getDeposit()).intValue();
            int WITHDRAW = new BigDecimal(user.getWithdraw()).intValue();
            int TOTAL = DEPOSIT + WITHDRAW;
            if(Amnt == 0) {
                makeText(this,"Select bet amount",LENGTH_SHORT).show();
            } else if(Nmbr == 0) {
                makeText(this,"Choose fruit",LENGTH_SHORT).show();
            } else if(DEPOSIT < Amnt && WITHDRAW < Amnt && TOTAL < Amnt) {
                makeText(this,"You have not enough balance",LENGTH_SHORT).show();
            } else {
                LightOnOff(true); finalList = new ArrayList<>(); isShow = true;
                slotMediaPlayer = MediaPlayer.create(this, R.raw.slot);
                slotMediaPlayer.setLooping(true); slotMediaPlayer.start();
                rv1.setAdapter(new JackpotAdapter(this, 1, true));
                rv2.setAdapter(new JackpotAdapter(this, 2, false));
                rv3.setAdapter(new JackpotAdapter(this, 3, true));
                rv4.setAdapter(new JackpotAdapter(this, 4, false));
                rv5.setAdapter(new JackpotAdapter(this, 5, true));
            }
        });
        amtView = findViewById(R.id.amountView); betView = findViewById(R.id.betView);
        amtView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        amtView.setHasFixedSize(false);amtView.setAdapter(new AmountAdapter(false,2));
        betView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        betView.setHasFixedSize(false);betView.setAdapter(new BetAdapter(false,2));
        findViewById(R.id.ivMenu).setOnClickListener(view -> {
            if(isShow) {
                updateUser(this,calWallet(Amnt)[0],calWallet(Amnt)[1],String.valueOf(0));
            }
            if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
                winMediaPlayer.stop();
            }
            if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
                looseMediaPlayer.stop();
            }
            if(slotMediaPlayer != null && slotMediaPlayer.isPlaying()) {
                slotMediaPlayer.stop();
            }
            if(handlr != null && runable != null) {
                handlr.removeCallbacks(runable);
            }
            finish();
        });
        if(!new String(Base64.decode(BuildConfig.PACKAGE,Base64.DEFAULT)).equals(BuildConfig.APPLICATION_ID)) {
            finish();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        USER.observe(this, user -> {
            BigDecimal bal = new BigDecimal(user.getDeposit()).add(new BigDecimal(user.getWithdraw()));
            ((TextView)findViewById(R.id.tvBal)).setText("₹ " + bal);
        });
    }

    private class JackpotAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private int spin = 0;
        private int no = 0;
        private final int type;
        private Runnable runnable;
        private final Context ctx;
        private final boolean isB2T;
        private final Handler handler;
        private final List<Jackpot> jackpotList;

        JackpotAdapter(Context ctx,int type,boolean b2t) {
            this.ctx = ctx;
            this.isB2T = b2t;
            this.type = type;
            this.handler = new Handler();
            this.jackpotList = new ArrayList<>();
            for(int ii=0;ii<10;ii++) {
                String[] title = new String[]{"apple", "pineapple", "banana", "grape", "guava", "lychee", "orange", "dates", "watermelon",
                        "coconut", "cherry", "peach", "strawberry", "mango"};
                for (int i = 0; i < title.length; i++) {
                    int[] icon = new int[]{R.drawable.apple, R.drawable.pineapple, R.drawable.banana, R.drawable.grape, R.drawable.guava,
                            R.drawable.lychee, R.drawable.orange, R.drawable.dates, R.drawable.watermelon, R.drawable.coconut, R.drawable.cherry,
                            R.drawable.peach, R.drawable.strawberry, R.drawable.mango};
                    jackpotList.add(new Jackpot(title[i], icon[i]));
                }
            }
            Collections.shuffle(jackpotList);
        }

        @NonNull
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.jakpot,parent,false);
            return new CateView(view);
        }

        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            CateView cateView = (CateView) holder;
            cateView.title.setText(jackpotList.get(no).getTitle());
            cateView.icon.setImageResource(jackpotList.get(no).getIcon());
            if (isB2T) {
                cateView.itemView.setAnimation(AnimationUtils.loadAnimation(ctx, R.anim.b2t));
            } else {
                cateView.itemView.setAnimation(AnimationUtils.loadAnimation(ctx, R.anim.t2b));
            }
            if(type == 1) {
                if(spin < 50) {
                    RunningJackpotSlot();
                    spin++;
                } else {
                    finalList.add(jackpotList.get(no));
                }
            } else if(type == 2) {
                if(spin < 60) {
                    RunningJackpotSlot();
                    spin++;
                } else {
                    finalList.add(jackpotList.get(no));
                }
            } else if(type == 3) {
                if(spin < 70) {
                    RunningJackpotSlot();
                    spin++;
                } else {
                    finalList.add(jackpotList.get(no));
                }
            } else if(type == 4) {
                if(spin < 80) {
                    RunningJackpotSlot();
                    spin++;
                } else {
                    finalList.add(jackpotList.get(no));
                }
            } else if(type == 5) {
                if(spin < 90) {
                    RunningJackpotSlot();
                    spin++;
                } else {
                    finalList.add(jackpotList.get(no));handlr.removeCallbacks(runable);
                    LightOff();slotMediaPlayer.stop();int total = 0;String name = "";
                    for(int p = 0; p < finalList.size(); p++) {
                        Jackpot jackpot = finalList.get(p);
                        if(jackpot.getIcon() == Nmbr) {
                            total++;name = " " + jackpot.getTitle() + " slot";
                        }
                    }
                    if(total == 0) {
                        updateUser((Activity)ctx,calWallet(Amnt)[0],calWallet(Amnt)[1],String.valueOf(0));
                        playSound(looseMediaPlayer);
                        makeText(ctx,"Batter luck next time",LENGTH_SHORT).show();
                    } else {
                        int win = Amnt * 2 * total;
                        updateUser((Activity)ctx,calWallet(Amnt)[0],calWallet(Amnt)[1],String.valueOf(taxCal(win)));
                        anim.setVisibility(View.VISIBLE);anim.playAnimation();playSound(winMediaPlayer);
                        makeText(ctx,"Yeh! its a " + total + name ,LENGTH_SHORT).show();
                    }
                    Nmbr = 0;Amnt = 0; isShow = false;
                    betView.setAdapter(new BetAdapter(false,2));
                    amtView.setAdapter(new AmountAdapter(false,2));
                }
            }
        }

        @Override
        public int getItemCount() {
            return 1;
        }

        @SuppressLint("NotifyDataSetChanged")
        private void RunningJackpotSlot() {
            if(runnable != null && handler != null) {
                handler.removeCallbacks(runnable);
            }
            runnable = () -> {
                if(no == 4) {
                    no = 0;
                } else {
                    no++;
                }
                notifyDataSetChanged();
            };
            assert handler != null;
            handler.postDelayed(runnable,200);
        }

        private class CateView extends RecyclerView.ViewHolder {
            private final ImageView icon;
            private final TextView title;
            public CateView(@NonNull View itemView) {
                super(itemView);
                title = itemView.findViewById(R.id.tv);
                icon = itemView.findViewById(R.id.img);
            }
        }
    }

    private void LightOnOff(boolean on) {
        boolean isON = on;
        int[] list = new int[]{R.id.d1,R.id.d2,R.id.d3,R.id.d4,R.id.d5,R.id.d6,R.id.d7,R.id.d8,R.id.d9,R.id.d10,R.id.d11,R.id.d12,
                R.id.d13,R.id.d14,R.id.d15,R.id.d16,R.id.d17,R.id.d18,R.id.d19,R.id.d20,R.id.d21,R.id.d22,R.id.d23,R.id.d24,
                R.id.d25,R.id.d26,R.id.d27,R.id.d28,R.id.d29,R.id.d30,R.id.d31,R.id.d32,R.id.d33,R.id.d34,R.id.d35,R.id.d36,R.id.d37};
        for (int j : list) {
            if (isON) {
                findViewById(j).setBackgroundTintList(ColorStateList.valueOf(Color.GREEN));
                isON = false;
            } else {
                findViewById(j).setBackgroundTintList(ColorStateList.valueOf(Color.RED));
                isON = true;
            }
        }
        runable = () -> LightOnOff(!on);
        handlr.postDelayed(runable,600);
    }

    private void LightOff() {
        int[] list = new int[]{R.id.d1,R.id.d2,R.id.d3,R.id.d4,R.id.d5,R.id.d6,R.id.d7,R.id.d8,R.id.d9,R.id.d10,R.id.d11,R.id.d12,
                R.id.d13,R.id.d14,R.id.d15,R.id.d16,R.id.d17,R.id.d18,R.id.d19,R.id.d20,R.id.d21,R.id.d22,R.id.d23,R.id.d24,
                R.id.d25,R.id.d26,R.id.d27,R.id.d28,R.id.d29,R.id.d30,R.id.d31,R.id.d32,R.id.d33,R.id.d34,R.id.d35,R.id.d36,R.id.d37};
        for (int j : list) {
            findViewById(j).setBackgroundTintList(null);
        }
    }

    private void playSound(MediaPlayer mp) {
        try {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.pause();
                    mp.seekTo(0);
                }
                mp.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if(isShow) {
            updateUser(this,calWallet(Amnt)[0],calWallet(Amnt)[1],String.valueOf(0));
        }
        if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
            winMediaPlayer.stop();
        }
        if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
            looseMediaPlayer.stop();
        }
        if(slotMediaPlayer != null && slotMediaPlayer.isPlaying()) {
            slotMediaPlayer.stop();
        }
        if(handlr != null && runable != null) {
            handlr.removeCallbacks(runable);
        }
        finish();
    }

}