package com.friendvilla.bucksbuddy;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;
import static androidx.recyclerview.widget.LinearLayoutManager.HORIZONTAL;
import static com.friendvilla.bucksbuddy.MainActivity.USER;
import static com.friendvilla.bucksbuddy.Method.calWallet;
import static com.friendvilla.bucksbuddy.Method.title;
import static com.friendvilla.bucksbuddy.Method.updateUser;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.lifecycle.MutableLiveData;
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.controls.ScratchCard;
import com.friendvilla.bucksbuddy.model.User;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

public class ScratchActivity extends AppCompatActivity {

    private int Reward = 0;
    private boolean isShow = false;
    private RecyclerView amtView;
    private FrameLayout container;
    private final int[] a = new int[]{1,2,3};
    private MediaPlayer winMediaPlayer,looseMediaPlayer;
    public static MutableLiveData<Integer> AmountCard = new MutableLiveData<>();

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scratch);
        ((TextView)findViewById(R.id.tvTitle)).setText(title(this,getString(R.string.scratch_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);
        amtView = findViewById(R.id.amountView);AmountCard.setValue(0);
        amtView.setLayoutManager(new LinearLayoutManager(this,HORIZONTAL,false));
        amtView.setHasFixedSize(false);container = findViewById(R.id.frameView);
        winMediaPlayer = MediaPlayer.create(this,R.raw.win);
        looseMediaPlayer = MediaPlayer.create(this,R.raw.wrong);
        AmountCard.observe(this,integer -> {
            int DEPOSIT = new BigDecimal(user.getDeposit()).intValue();
            int WITHDRAW = new BigDecimal(user.getWithdraw()).intValue();
            int TOTAL = DEPOSIT + WITHDRAW; int betAmt = integer;
            if (betAmt != 0) {
                if(DEPOSIT < betAmt && WITHDRAW < betAmt && TOTAL < betAmt) {
                    AmountCard.setValue(0);
                    amtView.setAdapter(new AmountAdapter(false,4));
                    makeText(this,"You have not enough money",LENGTH_SHORT).show();
                } else {
                    container.removeAllViews();
                    Card(a[num(a.length)]);
                }
            }
        });
        findViewById(R.id.ivMenu).setOnClickListener(view -> {
            if(isShow) {
                assert AmountCard.getValue() != null;
                updateUser(this,calWallet(AmountCard.getValue())[0],calWallet(AmountCard.getValue())[1],String.valueOf(0));
            }
            if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
                winMediaPlayer.stop();
            }
            if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
                looseMediaPlayer.stop();
            }
            finish();
        });
        setDefaultView();
    }

    @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);
        });
    }

    @SuppressLint({"SetTextI18n", "InflateParams"})
    private void Card(int cNo) {
        final List<int[]> rList = new ArrayList<>();
        AtomicInteger win = new AtomicInteger();container.removeAllViews();
        final int[] Bln = new int[] {R.drawable.btr,R.drawable.luck};
        final int[] Won = new int[] {R.drawable.won1,R.drawable.won2};
        rList.add(new int[]{0, 1, 0, 0, 3, 0, 1, 0, 0, 2});
        rList.add(new int[]{1, 2, 0, 2, 5, 0, 3, 1, 0, 2});
        rList.add(new int[]{2, 1, 3, 6, 3, 0, 3, 0, 5, 2});
        rList.add(new int[]{3, 8, 7, 3, 3, 4, 4, 5, 0, 2});
        rList.add(new int[]{4, 10, 0, 8, 3, 5, 5, 0, 4, 6});
        rList.add(new int[]{5, 10, 5, 0, 6, 9, 8, 6, 0, 6});
        rList.add(new int[]{6, 7, 0, 10, 3, 7, 7, 15, 0, 8});
        rList.add(new int[]{7, 10, 8, 7, 8, 0, 8, 12, 8, 7});
        rList.add(new int[]{8, 15, 0, 8, 9, 9, 12, 8, 7, 9});
        rList.add(new int[]{9, 20, 0, 9, 8, 10, 15, 8, 11, 10});
        assert AmountCard.getValue() != null;View view;
        int[] fr = rList.get(AmountCard.getValue()-1);
        Reward = fr[new Random().nextInt(fr.length)];
        LayoutInflater inflater = LayoutInflater.from(this);
        if(cNo == 1) {
            view = inflater.inflate(R.layout.sc1,null);
        } else if(cNo == 2) {
            view = inflater.inflate(R.layout.sc2,null);
        } else {
            view = inflater.inflate(R.layout.sc3,null);
        }
        ScratchCard stv = view.findViewById(R.id.card);
        TextView txt = view.findViewById(R.id.txt);
        LottieAnimationView anim = view.findViewById(R.id.win);
        if(Reward == 0) {
            txt.setBackground(drawable(Bln));
        } else {
            txt.setText("₹ " + Reward);
            txt.setBackground(drawable(Won));
        }
        stv.setOnScratchListener((scratchCard, visiblePercent) -> {
            if (visiblePercent > 0.3) {
                scratchCard.setVisibility(View.INVISIBLE);
                if(Reward != 0) {
                    anim.setVisibility(View.VISIBLE);
                    anim.playAnimation(); win.set(Reward);
                    playSound(winMediaPlayer);
                } else {
                    playSound(looseMediaPlayer);
                }
                updateUser(this,calWallet(AmountCard.getValue())[0],calWallet(AmountCard.getValue())[1],String.valueOf(win.get()));
                setDefaultView();isShow = false;
            }
        });
        view.setAnimation(AnimationUtils.loadAnimation(ScratchActivity.this,R.anim.party));
        isShow = true; container.addView(view);
    }

    private void setDefaultView() {
        container.removeAllViews();
        LayoutInflater inflater = LayoutInflater.from(this);
        @SuppressLint("InflateParams")
        View view = inflater.inflate(R.layout.sc0,null);
        container.addView(view); AmountCard.setValue(0);isShow = false;
        amtView.setAdapter(new AmountAdapter(false,4));
    }

    private int num(int n) {
        return new Random().nextInt(n);
    }

    private Drawable drawable(int[] NS) {
        return AppCompatResources.getDrawable(this,NS[num(NS.length)]);
    }

    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) {
            assert AmountCard.getValue() != null;
            updateUser(this,calWallet(AmountCard.getValue())[0],calWallet(AmountCard.getValue())[1],String.valueOf(0));
        }
        if(winMediaPlayer != null && winMediaPlayer.isPlaying()) {
            winMediaPlayer.stop();
        }
        if(looseMediaPlayer != null && looseMediaPlayer.isPlaying()) {
            looseMediaPlayer.stop();
        }
        finish();
    }
}