package com.SpinMoney.SpinMoney;

import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;

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

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import static android.widget.Toast.makeText;
import static android.widget.Toast.LENGTH_SHORT;

public class MainActivity extends AppCompatActivity {

    private long exitTime = 0;
    public static TextView deposit,withdraw;
    private MediaPlayer coinsGainedMediaPlayer, wheelSpinMediaPlayer, clickButtonMediaPlayer;
    private final List<LuckyItem> data = new ArrayList<>();
    private LuckyWheelView luckyWheelView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ImageView dp = findViewById(R.id.dpp);
        TextView name = findViewById(R.id.name);
        TextView email = findViewById(R.id.email);
        deposit = findViewById(R.id.dep);
        withdraw = findViewById(R.id.with);
        RecyclerView recyclerView = findViewById(R.id.recyclermenu);
        DrawerLayout drawerLayout = findViewById(R.id.drawer);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.app_name, R.string.app_name);
        drawerLayout.addDrawerListener(toggle); toggle.syncState();
        deposit.setText(getResources().getString(R.string.rupee).replace("0",Utils.deposit));
        withdraw.setText(getResources().getString(R.string.rupee).replace("0",Utils.withdraw));
        if(!Utils.userDP.equals("")) {
            Picasso.get()
                    .load("http://spinorreward.xyz/admin/" + Utils.userDP.replace(" ", "%20"))
                    .placeholder(R.mipmap.logo_round)
                    .into(dp);
        }
        name.setText(Utils.userName);
        email.setText(Utils.userEmail);
        LinearLayoutManager llManager = new LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(llManager);
        recyclerView.setHasFixedSize(true);
        SidebarAdapter sidebarAdapter = new SidebarAdapter(this, drawerLayout);
        recyclerView.setAdapter(sidebarAdapter);
        coinsGainedMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.coin_gained);
        wheelSpinMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.spinner_sound);
        clickButtonMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.button_click);
        luckyWheelView = findViewById(R.id.luckyWheel);
        Button btnPlay = findViewById(R.id.btnplay);
        //fillWheel(); luckyWheelView.setData(data); luckyWheelView.setRound(2);
        if (isConnected(this)) {
            getLuckyWheel();
        } else {
            makeText(this,"No Connection Found",LENGTH_SHORT).show();
        }
        btnPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(Integer.parseInt(Utils.deposit)>=10) {
                    playWheelSpinSound();btnPlay.setEnabled(false);
                    int indexPosition = getRandomIndex();
                    luckyWheelView.startLuckyWheelWithTargetIndex(indexPosition);
                } else {
                    makeText(MainActivity.this,"Not Enough Deposit Money",LENGTH_SHORT).show();
                }
            }
        });
        findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,AddMoneyActivity.class)
                        .putExtra("type","deposit"));
            }
        });
        findViewById(R.id.withdraw).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this,AddMoneyActivity.class)
                        .putExtra("type","withdraw"));
            }
        });
        luckyWheelView.setLuckyRoundItemSelectedListener(new LuckyWheelView.LuckyRoundItemSelectedListener() {
            @Override
            public void LuckyRoundItemSelected(int index) {
                if (index != 0) {
                    index = index - 1;
                }
                int pointAdd = Integer.parseInt(data.get(index).text.replace("₹ ",""));
                if (pointAdd != 0) {
                    int dm = Integer.parseInt(Utils.deposit) - 10;
                    int wm = Integer.parseInt(Utils.withdraw) + pointAdd;
                    addPointOnline(dm,wm);
                    playCoinsGainedSound();
                } else {
                    int dm = Integer.parseInt(Utils.deposit) - 10;
                    int wm = Integer.parseInt(Utils.withdraw);
                    addPointOnline(dm,wm);
                }
                btnPlay.setEnabled(true);
            }
        });
    }

    private void getLuckyWheel() {
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=get_spinner_blocks";
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(JSON_URL, null, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                    JSONObject objJson;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        objJson = jsonArray.getJSONObject(i);
                        LuckyItem objItem = new LuckyItem();
                        objItem.text = "₹ " + objJson.getString(Constant.LUCKY_WHEEL_POINT);
                        objItem.icon = R.drawable.coins;
                        objItem.color = Color.parseColor(objJson.getString(Constant.LUCKY_WHEEL_BG));
                        data.add(objItem);
                    }
                    if (data.size() > 0) {
                        luckyWheelView.setData(data);
                        luckyWheelView.setRound(2);
                    }
                    ((ProgressBar)findViewById(R.id.progress)).setVisibility(View.GONE);
                } catch (Exception e) {
                    makeText(MainActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                makeText(MainActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    private void addPointOnline(int dm, int wm) {
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=update_wallet&user_id=" + Utils.userID + "&deposit=" + dm + "&withdraw=" + wm;
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(JSON_URL, null, new com.android.volley.Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject objJson = jsonArray.getJSONObject(i);
                        String msg = objJson.getString("msg");
                        int status = objJson.getInt("success");
                        getProfile();
                        makeText(MainActivity.this, msg, LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    makeText(MainActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new com.android.volley.Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                makeText(MainActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    private int getRandomIndex() {
        Random rand = new Random();
        return rand.nextInt(data.size() - 1);
    }

    private void getProfile(){
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=user_profile&id=" + Utils.getString(this,"UserId");
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        JsonObjectRequest objectRequest = new JsonObjectRequest(JSON_URL, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject objJson = jsonArray.getJSONObject(i);
                        Utils.userID = objJson.getString("user_id");
                        Utils.userName = objJson.getString("name");
                        Utils.userEmail = objJson.getString("email");
                        Utils.userDP = objJson.getString("user_pro_image");
                        Utils.userPhone = objJson.getString("phone");
                        Utils.deposit = objJson.getString("deposit");
                        Utils.withdraw = objJson.getString("withdraw");
                    }
                    deposit.setText(getResources().getString(R.string.rupee).replace("0",Utils.deposit));
                    withdraw.setText(getResources().getString(R.string.rupee).replace("0",Utils.withdraw));
                } catch (Exception e) {
                    makeText(MainActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                makeText(MainActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    private void fillWheel() {
        LuckyItem luckyItem1 = new LuckyItem();
        luckyItem1.text = "0";
        luckyItem1.icon = R.drawable.coins;
        luckyItem1.color = 0xffFFD823;
        data.add(luckyItem1);

        LuckyItem luckyItem2 = new LuckyItem();
        luckyItem2.text = "1";
        luckyItem2.icon = R.drawable.coins;
        luckyItem2.color = 0xffFF6600;
        data.add(luckyItem2);

        LuckyItem luckyItem3 = new LuckyItem();
        luckyItem3.text = "0";
        luckyItem3.icon = R.drawable.coins;
        luckyItem3.color = 0xffDE1112;
        data.add(luckyItem3);

        LuckyItem luckyItem4 = new LuckyItem();
        luckyItem4.text = "2";
        luckyItem4.icon = R.drawable.coins;
        luckyItem4.color = 0xff08952C;
        data.add(luckyItem4);

        LuckyItem luckyItem5 = new LuckyItem();
        luckyItem5.text = "0";
        luckyItem5.icon = R.drawable.coins;
        luckyItem5.color = 0xff104676;
        data.add(luckyItem5);

        LuckyItem luckyItem6 = new LuckyItem();
        luckyItem6.text = "1";
        luckyItem6.icon = R.drawable.coins;
        luckyItem6.color = 0xff00ABD4;
        data.add(luckyItem6);
    }

    @RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE)
    public static boolean isConnected(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        assert cm != null;
        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null && info.isConnected());
    }

    public void playCoinsGainedSound() {
        playSound(coinsGainedMediaPlayer);
    }
    public void playWheelSpinSound() {
        playSound(wheelSpinMediaPlayer);
    }
    public void playClickButtonSound() {
        playSound(clickButtonMediaPlayer);
    }
    public void playSound(MediaPlayer mp) {
        try {
            if (mp != null) {
                if (mp.isPlaying()) {
                    mp.pause();
                    mp.seekTo(0);
                    mp.start();
                } else {
                    mp.start();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            Toast.makeText(this,"Press Again To Exit", Toast.LENGTH_SHORT).show();
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }

}