package com.friendvilla.slotmachine;

import static com.friendvilla.slotmachine.SplashActivity.getAdSize;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import androidx.annotation.NonNull;
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.google.android.gms.ads.AdError;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.FullScreenContentCallback;
import com.google.android.gms.ads.LoadAdError;
import com.google.android.gms.ads.MobileAds;
import com.google.android.gms.ads.interstitial.InterstitialAd;
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback;
import com.google.android.material.navigation.NavigationView;

import java.util.Random;

public class MainActivity extends AppCompatActivity {

    private Dialog dialog;
    private MediaPlayer mpPlay,mp;
    private TextView balance;
    private boolean startNumber1 = false;
    private boolean startNumber2 = false;
    private boolean startNumber3 = false;
    private final boolean finishGame = false;
    private boolean startRotation = false;
    public static SharedPreferences sp;
    private InterstitialAd mInterstitial;
    public static SharedPreferences.Editor edit;
    private Runnable number1, number2,number3,checkWin;
    private ViewFlipper viewFlipper1,viewFlipper2,viewFlipper3;
    private Thread numberThread1,numberThread2,numberThread3,animationInProgress;

    @SuppressLint("InflateParams")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        MobileAds.initialize(this, initializationStatus -> {
            FrameLayout mContainer = findViewById(R.id.adView);
            AdView adView = new AdView(this);
            adView.setAdUnitId(getString(R.string.banner));
            mContainer.addView(adView);
            adView.setAdSize(getAdSize(this));
            adView.loadAd(new AdRequest.Builder().build());
        });loadInterstitialAd();mpPlay = MediaPlayer.create(this,R.raw.casino);
        mp = MediaPlayer.create(this,R.raw.win);mpPlay.setLooping(true);
        sp = getSharedPreferences(getString(R.string.app_name),MODE_PRIVATE);
        edit = sp.edit();balance = findViewById(R.id.bal);
        balance.setText(String.valueOf(sp.getInt("bal",0)));
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        assert getSupportActionBar() != null;
        DrawerLayout drawer = findViewById(R.id.drawer);
        NavigationView navigation = findViewById(R.id.nav_view);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        viewFlipper1 = findViewById(R.id.viewFlipper1);
        viewFlipper2 = findViewById(R.id.viewFlipper2);
        viewFlipper3 = findViewById(R.id.viewFlipper3);
        viewFlipper1.setInAnimation(this,R.anim.top);
        viewFlipper1.setOutAnimation(this,R.anim.bottom);
        viewFlipper2.setInAnimation(this,R.anim.top);
        viewFlipper2.setOutAnimation(this,R.anim.bottom);
        viewFlipper3.setInAnimation(this,R.anim.top);
        viewFlipper3.setOutAnimation(this,R.anim.bottom);
        initAllRunnablesAndThreds();numberThread1.start();
        numberThread2.start();numberThread3.start();
        animationInProgress.start();
        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) {
                new AlertDialog.Builder(this)
                        .setMessage(getString(R.string.sup))
                        .setPositiveButton("OK",(d,i) -> d.dismiss()).create().show();
            } else if (id == R.id.policy) {
                new AlertDialog.Builder(this)
                        .setMessage(getString(R.string.policytxt))
                        .setPositiveButton("OK",(d,i) -> d.dismiss()).create().show();
            }  else if (id == R.id.term) {
                new AlertDialog.Builder(this)
                        .setMessage(getString(R.string.policytxt))
                        .setPositiveButton("OK",(d,i) -> d.dismiss()).create().show();
            } else if (id == R.id.about) {
                new AlertDialog.Builder(this)
                        .setMessage(getString(R.string.abouttxt))
                        .setPositiveButton("OK",(d,i) -> d.dismiss()).create().show();
            } else if (id == R.id.share) {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, "Share App");
                String playstore = "\n Download App From This Link:\n\n" + "https://play.google.com/store/apps/details?id=" + getPackageName();
                i.putExtra(Intent.EXTRA_TEXT, playstore);
                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;
        });
        dialog = new Dialog(this);dialog.setContentView(R.layout.win);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        dialog.setCancelable(false);
        findViewById(R.id.spin).setOnClickListener(view -> {
            if(mInterstitial != null) {
                mInterstitial.setFullScreenContentCallback(new FullScreenContentCallback() {
                    @Override
                    public void onAdDismissedFullScreenContent() {
                        super.onAdDismissedFullScreenContent();
                        loadInterstitialAd();
                        runSlot();
                    }
                    @Override
                    public void onAdFailedToShowFullScreenContent(@NonNull AdError adError) {
                        super.onAdFailedToShowFullScreenContent(adError);
                        new AlertDialog.Builder(MainActivity.this)
                                .setMessage("Spin not available now, try again later!").setCancelable(false)
                                .setPositiveButton("OK",(dialog,i) -> dialog.dismiss()).show();
                    }
                });
                mInterstitial.show(this);
            } else {
                new AlertDialog.Builder(this)
                        .setMessage("Spin not available now, try again later!").setCancelable(false)
                        .setPositiveButton("OK",(dialog,i) -> dialog.dismiss()).show();
            }
        });
        findViewById(R.id.container).setOnClickListener(view -> {
            WithdrawBox withdrawBox = new WithdrawBox(this);
            withdrawBox.show(getSupportFragmentManager(),"withdraw");
        });
    }

    private void runSlot() {
        if (!startRotation) {
            startNumber1 = true; startNumber2 = true;
            startNumber3 = true; startRotation = true;
            playSound(true);
        }
    }

    @SuppressWarnings("ALL")
    private void initAllRunnablesAndThreds() {
        number1 = () -> viewFlipper1.showNext();
        number2 = () -> viewFlipper2.showNext();
        number3 = () -> viewFlipper3.showNext();
        checkWin = () -> {
            if (!startNumber1&!startNumber2&!startNumber3) {
                int number1 = viewFlipper1.getDisplayedChild();
                int number2 = viewFlipper2.getDisplayedChild();
                int number3 = viewFlipper3.getDisplayedChild();
                String combi = number1+ "" + number2;
                String combo = number2+ ""  + number3;
                String comb = number1+ ""  + number3;
                String combination = number1+ "" + number2 + number3;
                if(combination.equals("012")) {
                    playSound(false);
                    showPopupWinWindow("20");
                } else if(combination.equals("101")) {
                    playSound(false);
                    showPopupWinWindow("30");
                } else if(combination.equals("220")) {
                    playSound(false);
                    showPopupWinWindow("50");
                } else {
                    if(combi.equals("01") || combo.equals("12") || comb.equals("02")) {
                        playSound(false);
                        showPopupWinWindow("8");
                    } else if(combi.equals("10") || combo.equals("01") || comb.equals("11")) {
                        playSound(false);
                        showPopupWinWindow("7");
                    } else if(combi.equals("22") || combo.equals("20") || comb.equals("20")) {
                        playSound(false);
                        showPopupWinWindow("10");
                    } else {
                        playSound(false);
                        int ran = new Random().nextInt(7);
                        showPopupWinWindow(String.valueOf(ran));
                    }
                }
            }
        };
        numberThread1 = new Thread() {
            final Random r = new Random();
            int speed1,speed2,speed3;
            int i;
            @Override
            public void run() {
                while (!finishGame) {
                    while (startNumber1) {
                        speed1 = r.nextInt(30);
                        speed2 = r.nextInt(30);
                        speed3 = r.nextInt(30);
                        try {
                            for (i = 0; i < speed1; ++i) {
                                runOnUiThread(number1);
                                sleep(100);
                            }
                            for (i = 0; i < speed2; ++i) {
                                runOnUiThread(number1);
                                sleep(200);
                            }
                            for (i = 0; i < speed3; ++i) {
                                runOnUiThread(number1);
                                sleep(300);
                            }
                        } catch (Exception c) {
                            //do nothing
                        }
                        startNumber1 = false;
                        stopRotationInProgress();
                        runOnUiThread(checkWin);
                    }
                }
            }
        };
        numberThread2 = new Thread() {
            final Random r = new Random();
            int speed1, speed2,speed3;
            int i;
            @Override
            public void run() {
                while (!finishGame) {
                    while (startNumber2) {
                        speed1 = r.nextInt(30);
                        speed2 = r.nextInt(30);
                        speed3 = r.nextInt(30);
                        try {
                            for (i = 0; i < speed1; ++i) {
                                runOnUiThread(number2);
                                sleep(100);
                            }
                            for (i = 0; i < speed2; ++i) {
                                runOnUiThread(number2);
                                sleep(200);
                            }
                            for (i = 0; i < speed3; ++i) {
                                runOnUiThread(number2);
                                sleep(300);
                            }
                        } catch (Exception c) {
                            //do nothing
                        }
                        startNumber2 = false;
                        stopRotationInProgress();
                        runOnUiThread(checkWin);
                    }
                }
            }
        };
        numberThread3 = new Thread() {
            final Random r = new Random();
            int speed1, speed2,speed3;
            int i;
            @Override
            public void run() {
                while (!finishGame) {
                    while (startNumber3) {
                        speed1 = r.nextInt(30);
                        speed2 = r.nextInt(30);
                        speed3 = r.nextInt(30);
                        try {
                            for (i = 0; i < speed1; ++i) {
                                runOnUiThread(number3);
                                sleep(100);
                            }
                            for (i = 0; i < speed2; ++i) {
                                runOnUiThread(number3);
                                sleep(200);
                            }
                            for (i = 0; i < speed3; ++i) {
                                runOnUiThread(number3);
                                sleep(300);
                            }
                        } catch (Exception c) {
                            //do nothing
                        }
                        startNumber3 = false;
                        stopRotationInProgress();
                        runOnUiThread(checkWin);
                    }
                }
            }
        };
        animationInProgress = new Thread() {
            @Override
            public void run() {
                while (!finishGame) {
                    while (startRotation) {
                        try {
                            sleep(500);
                        } catch (Exception c) {
                            //do nothing
                        }
                    }
                }
            }
        };
    }

    private void stopRotationInProgress() {
        if (!startNumber1&!startNumber2&!startNumber3) {
            startRotation = false;
        }
    }

    private void loadInterstitialAd() {
        AdRequest adRequest = new AdRequest.Builder().build();
        InterstitialAd.load(this, getString(R.string.interstitial), adRequest, new InterstitialAdLoadCallback() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                loadInterstitialAd();
            }

            @Override
            public void onAdLoaded(@NonNull InterstitialAd interstitialAd) {
                super.onAdLoaded(interstitialAd);
                mInterstitial = interstitialAd;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        balance.setText(String.valueOf(sp.getInt("bal",0)));
    }

    private void showPopupWinWindow(String tk) {
        if(Integer.parseInt(tk) > 0) {
            int bal = sp.getInt("bal",0) + Integer.parseInt(tk);
            edit.putInt("bal",bal);edit.apply();
        }
        balance.setText(String.valueOf(sp.getInt("bal",0)));
        TextView coin = dialog.findViewById(R.id.coin);
        coin.setText(tk);dialog.findViewById(R.id.ok).setOnClickListener(view -> {
            if (dialog != null && dialog.isShowing()) {
                if (mp.isPlaying()) {
                    mp.stop();mp.release();
                    mp = MediaPlayer.create(this,R.raw.win);
                }
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void playSound(boolean isMusic) {
        if (mpPlay.isPlaying()) {
            mpPlay.stop();mpPlay.release();
            mpPlay = MediaPlayer.create(this,R.raw.casino);
            mpPlay.setLooping(true);
        }
        if(isMusic) {
            mpPlay.start();
        } else {
            mp.start();
        }
    }

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