package com.SpinMoney.SpinMoney;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

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 org.json.JSONArray;
import org.json.JSONObject;

import static android.widget.Toast.LENGTH_SHORT;
import static android.widget.Toast.makeText;

public class SplashActivity extends AppCompatActivity {

    private View loginView, registerView, forgotView;
    private RelativeLayout splashView;
    private EditText logEmail,regEmail,edtEmail,logPass,regPass,regName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        loginView = findViewById(R.id.login);
        registerView = findViewById(R.id.register);
        forgotView = findViewById(R.id.forgotpass);
        splashView = findViewById(R.id.splash);
        logEmail = loginView.findViewById(R.id.edit_email);
        logPass = loginView.findViewById(R.id.edit_password);
        Button login = loginView.findViewById(R.id.bttn_update);
        TextView forgetPass = loginView.findViewById(R.id.txt_forgot);
        Button goReg = loginView.findViewById(R.id.btn_create);
        regName = registerView.findViewById(R.id.edt_user);
        regEmail = registerView.findViewById(R.id.edt_email);
        regPass = registerView.findViewById(R.id.edt_password);
        Button register = registerView.findViewById(R.id.btn_update);
        CheckBox goPolicy = registerView.findViewById(R.id.checkbox);
        Button goLog = registerView.findViewById(R.id.btn_login);
        edtEmail = forgotView.findViewById(R.id.etUserName);
        Button forgot = forgotView.findViewById(R.id.btnForgot);
        goReg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                splashView.setVisibility(View.GONE);
                loginView.setVisibility(View.GONE);
                forgotView.setVisibility(View.GONE);
                registerView.setVisibility(View.VISIBLE);
            }
        });
        goLog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                splashView.setVisibility(View.GONE);
                registerView.setVisibility(View.GONE);
                forgotView.setVisibility(View.GONE);
                loginView.setVisibility(View.VISIBLE);
            }
        });
        forgetPass.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                splashView.setVisibility(View.GONE);
                registerView.setVisibility(View.GONE);
                loginView.setVisibility(View.GONE);
                forgotView.setVisibility(View.VISIBLE);
            }
        });
        goPolicy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                makeText(SplashActivity.this,"Click & Hold to Read Policy",LENGTH_SHORT).show();
            }
        });
        goPolicy.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Intent it = new Intent(Intent.ACTION_VIEW);
                it.setData(Uri.parse("https://azzurteam.blogspot.com/2020/12/privacy-policy-this-page-is-used-to.html"));
                startActivity(it);
                return false;
            }
        });
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(logEmail.getText().toString().equals("")||logPass.getText().toString().equals("")){
                    makeText(SplashActivity.this,"fill all properly",LENGTH_SHORT).show();
                } else if(!logEmail.getText().toString().contains("@")||!logEmail.getText().toString().contains(".")){
                    makeText(SplashActivity.this,"invalid email",LENGTH_SHORT).show();
                } else if(logPass.getText().toString().length()<6){
                    makeText(SplashActivity.this,"min password length is 6",LENGTH_SHORT).show();
                } else if (!MainActivity.isConnected(SplashActivity.this)) {
                    makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
                } else {
                    ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.VISIBLE);
                    loginTask(logEmail.getText().toString(),logPass.getText().toString());
                }
            }
        });
        register.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(regName.getText().toString().equals("")||regEmail.getText().toString().equals("")||regPass.getText().toString().equals("")){
                    makeText(SplashActivity.this,"fill all properly",LENGTH_SHORT).show();
                } else if(regName.getText().toString().toLowerCase().contains("admin")||regName.getText().toString().toLowerCase().contains("administrator")
                        ||regName.getText().toString().toLowerCase().contains("makeeasy")||regName.getText().toString().toLowerCase().contains("moderator")){
                    makeText(SplashActivity.this,"name not allowed",LENGTH_SHORT).show();
                } else if(!regEmail.getText().toString().contains("@")||!regEmail.getText().toString().contains(".")){
                    makeText(SplashActivity.this,"invalid email",LENGTH_SHORT).show();
                } else if(regPass.getText().toString().length()<6){
                    makeText(SplashActivity.this,"min password length is 6",LENGTH_SHORT).show();
                } else if(!goPolicy.isChecked()){
                    makeText(SplashActivity.this,"accept terms and policy",LENGTH_SHORT).show();
                } else if (!MainActivity.isConnected(SplashActivity.this)) {
                    makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
                } else {
                    ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.VISIBLE);
                    registrationTask(regName.getText().toString(),regEmail.getText().toString(),regPass.getText().toString());
                }
            }
        });
        forgot.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!edtEmail.getText().toString().contains("@")||!edtEmail.getText().toString().contains(".")){
                    makeText(SplashActivity.this,"invalid email",LENGTH_SHORT).show();
                } else if (!MainActivity.isConnected(SplashActivity.this)) {
                    makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
                } else {
                    ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.VISIBLE);
                    getPassword(edtEmail.getText().toString());
                }
            }
        });

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (Utils.getBoolean(SplashActivity.this,"isLogin")) {
                    if (MainActivity.isConnected(SplashActivity.this)) {
                        getProfile();
                    } else {
                        makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
                    }
                } else{
                    if (MainActivity.isConnected(SplashActivity.this)) {
                        splashView.setVisibility(View.GONE);
                        registerView.setVisibility(View.GONE);
                        forgotView.setVisibility(View.GONE);
                        loginView.setVisibility(View.VISIBLE);
                    } else {
                        makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
                    }
                }
            }
        },1000);

    }

    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");
                    }
                    Intent i = new Intent(SplashActivity.this,MainActivity.class);
                    startActivity(i); finish();
                } catch (Exception e) {
                    makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                makeText(SplashActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    private void loginTask(String email,String password){
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=user_login&email=" + email + "&password=" + password;
        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");
                        String msg = objJson.getString("msg");
                        int ustatus = objJson.getInt("success");
                        if(ustatus==0){
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                        } else if(ustatus==1){
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            Utils.saveTag(SplashActivity.this,"isLogin",true);
                            Utils.saveTag(SplashActivity.this,"UserId",Utils.userID);
                            Intent in = new Intent(SplashActivity.this,MainActivity.class);
                            startActivity(in); finish();
                        }
                    }
                } catch (Exception e) {
                    ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                    makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                makeText(SplashActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    private void registrationTask(String name,String email,String password){
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=user_register&name=" + name + "&email=" + email + "&password=" + password + "&phone=0000000000";
        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);
                        String msg = objJson.getString("msg");
                        int status = objJson.getInt("success");
                        if(status ==0){
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                        } else if(status==1){
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                            logEmail.setText(email); logPass.setText(password);
                            splashView.setVisibility(View.GONE);
                            registerView.setVisibility(View.GONE);
                            forgotView.setVisibility(View.GONE);
                            loginView.setVisibility(View.VISIBLE);
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.VISIBLE);
                            loginTask(email,password);
                        } else {
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {
                    ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                    makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                makeText(SplashActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

    private void getPassword(String email){
        String JSON_URL = "http://spinorreward.xyz/admin/api.php?method=forgot_pass&email=" + email;
        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);
                        String msg = objJson.getString("msg");
                        int status = objJson.getInt("success");
                        if(status ==0){
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                        } else if(status==1){
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                            splashView.setVisibility(View.GONE);
                            registerView.setVisibility(View.GONE);
                            forgotView.setVisibility(View.GONE);
                            loginView.setVisibility(View.VISIBLE);
                        } else {
                            ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                            makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                        }
                    }
                } catch (Exception e) {
                    ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                    makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                ((ProgressBar)findViewById(R.id.pro)).setVisibility(View.GONE);
                makeText(SplashActivity.this,error.getMessage(),LENGTH_SHORT).show();
            }
        });
        requestQueue.add(objectRequest);
    }

}