package com.makeeasy.dailyinterest;

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

import static com.makeeasy.dailyinterest.Constant.HOST_NAME;
import static com.makeeasy.dailyinterest.Constant.hideLoader;
import static com.makeeasy.dailyinterest.Constant.isConnected;
import static com.makeeasy.dailyinterest.Constant.showLoader;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

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

@SuppressLint("CustomSplashScreen")
public class SplashActivity extends AppCompatActivity {

    private String nnn = "";
    private RelativeLayout splashView,registerView,loginView,forgetView;
    private EditText logEmail,regEmail,edtEmail,logPass,regPass,regCode,regName,regMob;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
        splashView = findViewById(R.id.splashView);
        registerView = findViewById(R.id.registerView);
        loginView = findViewById(R.id.loginView);
        forgetView = findViewById(R.id.forgotView);
        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);
        TextView 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);
        regMob = registerView.findViewById(R.id.edt_mobile);
        regCode = registerView.findViewById(R.id.code);
        Button register = registerView.findViewById(R.id.btn_update);
        CheckBox goPolicy = registerView.findViewById(R.id.checkbox);
        TextView goLog = registerView.findViewById(R.id.btn_login);
        edtEmail = forgetView.findViewById(R.id.etUserName);
        Button forgot = forgetView.findViewById(R.id.btnForgot);
        goReg.setOnClickListener(v -> {
            splashView.setVisibility(View.GONE);
            loginView.setVisibility(View.GONE);
            forgetView.setVisibility(View.GONE);
            registerView.setVisibility(View.VISIBLE);
        });
        goLog.setOnClickListener(v -> {
            splashView.setVisibility(View.GONE);
            registerView.setVisibility(View.GONE);
            forgetView.setVisibility(View.GONE);
            loginView.setVisibility(View.VISIBLE);
        });
        forgetPass.setOnClickListener(v -> {
            splashView.setVisibility(View.GONE);
            registerView.setVisibility(View.GONE);
            loginView.setVisibility(View.GONE);
            forgetView.setVisibility(View.VISIBLE);
        });
        goPolicy.setOnClickListener(v -> makeText(this,"Click & Hold to Read Policy",LENGTH_SHORT).show());
        goPolicy.setOnLongClickListener(v -> {
            Intent it = new Intent(Intent.ACTION_VIEW);
            it.setData(Uri.parse(getString(R.string.tos)));
            startActivity(it);
            return false;
        });
        login.setOnClickListener(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 (!isConnected(SplashActivity.this)) {
                makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
            } else {
                loginTask(logEmail.getText().toString(),logPass.getText().toString());
            }
        });
        register.setOnClickListener(v -> {
            if(regName.getText().toString().equals("")||regEmail.getText().toString().equals("")||regPass.getText().toString().equals("")||regMob.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(regMob.getText().toString().length()<10){
                makeText(SplashActivity.this,"invalid phone number",LENGTH_SHORT).show();
            } else if(!goPolicy.isChecked()){
                makeText(SplashActivity.this,"accept terms and policy",LENGTH_SHORT).show();
            } else if (!isConnected(SplashActivity.this)) {
                makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
            } else {
                registrationTask(regName.getText().toString(), regEmail.getText().toString(), regPass.getText().toString(), regMob.getText().toString());
            }
        });
        forgot.setOnClickListener(v -> {
            if(!edtEmail.getText().toString().contains("@")||!edtEmail.getText().toString().contains(".")){
                makeText(SplashActivity.this,"invalid email",LENGTH_SHORT).show();
            } else if (!isConnected(SplashActivity.this)) {
                makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
            } else {
                getPassword(edtEmail.getText().toString());
            }
        });
        if(isConnected(this)) {
            String JSON_URL = HOST_NAME + "api.php?method=get_app_details";
            Volley.newRequestQueue(this).add(new JsonObjectRequest(JSON_URL, response -> {
                try {
                    JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                    JSONObject objJson;
                    for (int i = 0; i < jsonArray.length(); i++) {
                        objJson = jsonArray.getJSONObject(i);
                        Utils.CashFreeId = objJson.getString("app_author");
                        Utils.CashFreeUpi = objJson.getString("code");
                        Utils.Rate = objJson.getString("rate");
                        Utils.Link = objJson.getString("app_website");
                        Utils.Version = objJson.getString("app_version");
                    }
                    if (Utils.getBoolean(SplashActivity.this,"isLogin")) {
                        getProfile();
                    } else {
                        splashView.setVisibility(View.GONE);
                        registerView.setVisibility(View.GONE);
                        forgetView.setVisibility(View.GONE);
                        loginView.setVisibility(View.VISIBLE);
                    }
                } catch (Exception e) {
                    makeText(this,e.getMessage(),LENGTH_SHORT).show();
                }
            }, error -> makeText(this,error.getMessage(),LENGTH_SHORT).show()));
        } else {
            makeText(SplashActivity.this,"No Connection Found",LENGTH_SHORT).show();
        }
        findViewById(R.id.verify).setOnClickListener(v -> {
            String code = regCode.getText().toString(); showLoader(this,"");
            if(!code.equals("")) {
                Volley.newRequestQueue(this).add(new JsonObjectRequest(HOST_NAME + "api.php?method=verify_code&rcode=" + code, response -> {
                    try {
                        JSONObject objJson = null;
                        String success = null,msg = null;
                        JSONArray jsonArray = response.getJSONArray(Constant.ARRAY_NAME);
                        for (int i = 0; i < jsonArray.length(); i++) {
                            objJson = jsonArray.getJSONObject(i);
                            success = objJson.getString("success");
                            msg = objJson.getString("msg");
                        }
                        assert success != null;
                        if(success.equals("1")) {
                            nnn = objJson.getString("name");
                        }
                        hideLoader();
                        makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                    } catch (Exception e) {
                        makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
                    }
                }, error -> {
                    hideLoader();
                    makeText(SplashActivity.this, error.getMessage(), LENGTH_SHORT).show();
                }));
            } else {
                hideLoader();
                makeText(SplashActivity.this,"refer code blank",LENGTH_SHORT).show();
            }
        });
    }

    private void getProfile() {
        String JSON_URL = HOST_NAME + "api.php?method=user_profile&id=" + Utils.getString(this,"UserId");
        Volley.newRequestQueue(this).add(new JsonObjectRequest(JSON_URL, 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);
                hideLoader(); startActivity(i); finish();
            } catch (Exception e) {
                hideLoader();
                makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> {
            hideLoader();
            makeText(SplashActivity.this, error.getMessage(), LENGTH_SHORT).show();
        }));
    }

    private void loginTask(String email,String password) {
        showLoader(this,"");
        String JSON_URL = HOST_NAME + "api.php?method=user_login&email=" + email + "&password=" + password;
        Volley.newRequestQueue(this).add(new JsonObjectRequest(JSON_URL, 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){
                        hideLoader();
                        makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                    } else if(ustatus == 1){
                        hideLoader();
                        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) {
                hideLoader();
                makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> {
            hideLoader();
            makeText(SplashActivity.this,error.getMessage(),LENGTH_SHORT).show();
        }));
    }

    private void registrationTask(String name, String email, String password, String phone){
        @SuppressLint("HardwareIds")
        String deviceID = Settings.Secure.getString(getContentResolver(),Settings.Secure.ANDROID_ID);
        String referCode = deviceID.substring(0,6); showLoader(this,"");
        String JSON_URL = HOST_NAME + "api.php?method=user_register&name=" + name + "&email=" + email + "&password=" + password + "&phone=" + phone + "&code=" + referCode + "&referby=" + nnn;
        Volley.newRequestQueue(this).add(new JsonObjectRequest(JSON_URL, 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) {
                        hideLoader();
                        makeText(SplashActivity.this, msg, LENGTH_SHORT).show();
                    } else if(status== 1) {
                        hideLoader();
                        makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                        logEmail.setText(email); logPass.setText(password);
                        splashView.setVisibility(View.GONE);
                        registerView.setVisibility(View.GONE);
                        forgetView.setVisibility(View.GONE);
                        loginView.setVisibility(View.VISIBLE);
                        loginTask(email,password);
                    } else {
                        hideLoader();
                        makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                hideLoader();
                makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> {
            hideLoader();
            makeText(SplashActivity.this,error.getMessage(),LENGTH_SHORT).show();
        }));
    }

    private void getPassword(String email) {
        showLoader(this,"");
        String JSON_URL = HOST_NAME + "api.php?method=forgot_pass&email=" + email;
        Volley.newRequestQueue(this).add(new JsonObjectRequest(JSON_URL, 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){
                        hideLoader();
                        makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                    } else if(status == 1){
                        hideLoader();
                        makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                        splashView.setVisibility(View.GONE);
                        registerView.setVisibility(View.GONE);
                        forgetView.setVisibility(View.GONE);
                        loginView.setVisibility(View.VISIBLE);
                    } else {
                        hideLoader();
                        makeText(SplashActivity.this,msg,LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                hideLoader();
                makeText(SplashActivity.this,e.getMessage(),LENGTH_SHORT).show();
            }
        }, error -> {
            hideLoader();
            makeText(SplashActivity.this,error.getMessage(),LENGTH_SHORT).show();
        }));
    }
}