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 static com.friendvilla.bucksbuddy.controls.Constant.spinList;

import android.animation.Animator;
import android.annotation.SuppressLint;
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.View;
import android.widget.TextView;

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.User;

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

public class SpinActivity extends AppCompatActivity {

    private Handler handler;
    private Runnable runnable;
    private LottieAnimationView anim;
    private boolean isShow = false;
    public static int Number = 0,Amount = 0;
    private LuckyWheelView luckyWheelView;
    private final List<LuckyItem> data = new ArrayList<>();
    private MediaPlayer winMediaPlayer,wheelSpinMediaPlayer,looseMediaPlayer;

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spin);
        ((TextView)findViewById(R.id.tvTitle)).setText(title(this,getString(R.string.spin_win),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);
        anim = findViewById(R.id.win);handler = new Handler();
        luckyWheelView = findViewById(R.id.luckyWheel);
        winMediaPlayer = MediaPlayer.create(this,R.raw.win);
        looseMediaPlayer = MediaPlayer.create(this,R.raw.wrong);
        wheelSpinMediaPlayer = MediaPlayer.create(this,R.raw.music);
        RecyclerView betView = findViewById(R.id.betView);
        RecyclerView amtView = findViewById(R.id.amountView);
        betView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        amtView.setLayoutManager(new LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false));
        betView.setHasFixedSize(false);amtView.setHasFixedSize(false);
        findViewById(R.id.ivMenu).setOnClickListener(view -> {
            if(isShow) {
                updateUser(this,calWallet(Amount)[0],calWallet(Amount)[1],String.valueOf(0));
            }
            if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
                winMediaPlayer.stop();
            }
            if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
                looseMediaPlayer.stop();
            }
            if(handler != null && runnable != null) {
                handler.removeCallbacks(runnable);
            }
            finish();
        });
        fillWheel(); luckyWheelView.setRound(12);
        luckyWheelView.setOnClickListener(v -> {
            int DEPOSIT = new BigDecimal(user.getDeposit()).intValue();
            int WITHDRAW = new BigDecimal(user.getWithdraw()).intValue();
            int TOTAL = DEPOSIT + WITHDRAW;
            if(Amount == 0) {
                makeText(this,"Select bet amount",LENGTH_SHORT).show();
            } else if(Number == 0) {
                makeText(this,"Choose number",LENGTH_SHORT).show();
            } else if(DEPOSIT < Amount && WITHDRAW < Amount && TOTAL < Amount) {
                makeText(this,"You have not enough balance",LENGTH_SHORT).show();
            } else {
                LightOnOff(true);isShow = true;
                playSound(wheelSpinMediaPlayer);
                luckyWheelView.setClickable(false);
                int indexPosition = new Random().nextInt(data.size());
                luckyWheelView.startLuckyWheelWithTargetIndex(indexPosition);
            }
        });
        luckyWheelView.setLuckyRoundItemSelectedListener(index -> {
            handler.removeCallbacks(runnable);LightOff();
            if (index != 0) { index = index - 1; }
            luckyWheelView.setClickable(true);
            if(spinList[index] == Number) {
                anim.addAnimatorListener(new Animator.AnimatorListener() {
                    @Override
                    public void onAnimationStart(Animator animation) { }
                    @Override
                    public void onAnimationEnd(Animator animation) {
                        anim.setVisibility(View.GONE);
                    }
                    @Override
                    public void onAnimationCancel(Animator animation) { }
                    @Override
                    public void onAnimationRepeat(Animator animation) { }
                });
                playSound(winMediaPlayer); int win = Amount * Number;
                updateUser(this,calWallet(Amount)[0],calWallet(Amount)[1],String.valueOf(taxCal(win)));
                anim.setVisibility(View.VISIBLE);anim.playAnimation();
                makeText(this,"Yeh! its " + spinList[index],LENGTH_SHORT).show();
            } else {
                playSound(looseMediaPlayer);
                makeText(this,"Opps! its " + spinList[index],LENGTH_SHORT).show();
                updateUser(this,calWallet(Amount)[0],calWallet(Amount)[1],String.valueOf(0));
            }
            Number = 0; Amount = 0; isShow = false;
            betView.setAdapter(new BetAdapter(false,1));
            amtView.setAdapter(new AmountAdapter(false,1));
        });
        betView.setAdapter(new BetAdapter(false,1));
        amtView.setAdapter(new AmountAdapter(false,1));
        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 void fillWheel() {
        for (int i : spinList) {
            int clr = Color.parseColor("#" +
                    new Random().nextInt(9) +
                    new Random().nextInt(9) +
                    new Random().nextInt(9) +
                    new Random().nextInt(9) +
                    new Random().nextInt(9) +
                    new Random().nextInt(9));
            data.add(new LuckyItem("" + i,R.drawable.coins,clr));
        }
        luckyWheelView.setData(data);
    }

    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};
        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;
            }
        }
        runnable = () -> LightOnOff(!on);
        handler.postDelayed(runnable,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};
        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(Amount)[0],calWallet(Amount)[1],String.valueOf(0));
        }
        if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
            winMediaPlayer.stop();
        }
        if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
            looseMediaPlayer.stop();
        }
        if(wheelSpinMediaPlayer != null && wheelSpinMediaPlayer.isPlaying()) {
            wheelSpinMediaPlayer.stop();
        }
        if(handler != null && runnable != null) {
            handler.removeCallbacks(runnable);
        }
        finish();
    }
}