package com.cscodetech.moverslorry.ui;


import static com.cscodetech.moverslorry.utils.SessionManager.login;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.cscodetech.moverslorry.R;
import com.cscodetech.moverslorry.databinding.ActivityVerificationBinding;
import com.cscodetech.moverslorry.model.Login;
import com.cscodetech.moverslorry.model.RestResponse;
import com.cscodetech.moverslorry.model.UserLogin;
import com.cscodetech.moverslorry.retrofit.APIClient;
import com.cscodetech.moverslorry.retrofit.GetResult;
import com.cscodetech.moverslorry.utils.CustPrograssbar;
import com.cscodetech.moverslorry.utils.Utility;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.onesignal.OneSignal;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;

public class VerificationActivity extends BaseActivity implements GetResult.MyListener {

    private ActivityVerificationBinding binding;
    CustPrograssbar custPrograssbar;
    UserLogin user;

    private int verificationOTP;

    private String owneri = "owner_id";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityVerificationBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        custPrograssbar = new CustPrograssbar();

        user = sessionmanager.getUserDetails();


        sendOTP(user.getCcode() + user.getMobile());

        binding.txtMobile.setText("Please, enter the verification code we send to your mobile " + user.getCcode() + user.getMobile());

        setOtpEditTextListener(binding.edOtp1, binding.edOtp2);
        setOtpEditTextListener(binding.edOtp2, binding.edOtp3);
        setOtpEditTextListener(binding.edOtp3, binding.edOtp4);
        setOtpEditTextListener(binding.edOtp4, binding.edOtp5);
        setOtpEditTextListener(binding.edOtp5, binding.edOtp6);
        setOtpEditTextListener(binding.edOtp6, binding.edOtp6);

    }

    private void setOtpEditTextListener(final EditText currentEditText, final EditText nextEditText) {
        currentEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Log.i("fdlk", "kgjd");

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count == 1 && s.length() == 1) {
                    nextEditText.requestFocus();
                } else if (count == 0) {
                    currentEditText.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                Log.i("fdlk", "kgjd");

            }
        });
    }

    private void sendOTP(String mobile) {

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("mobile", mobile);

            RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json"));
            Call<JsonObject> call = APIClient.getInterface().send_otp(bodyRequest);
            GetResult getResult = new GetResult(this);
            getResult.setMyListener(this);
            getResult.callForLogin(call, "1");
            custPrograssbar.prograssCreate(VerificationActivity.this);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    private void verifyCode(String code) {
        if (verificationOTP == Integer.parseInt(code)) {
            switch (Utility.getInstance().isvarification) {
                case 0:
                    Intent intent = new Intent(this, ChanegPasswordActivity.class);
                    intent.putExtra("phone", user.getMobile());
                    startActivity(intent);
                    finish();
                    break;
                case 1:
                    createUser();
                    break;
                case 2:
                    break;
                case 3:
                    finish();
                    break;
                default:
                    break;
            }
        }else {
            Toast.makeText(VerificationActivity.this,"Wrong OTP, please try again.",Toast.LENGTH_LONG).show();
        }
    }







    public void onBindClick(View view) {
        if (view.getId() == R.id.btn_verifyaccount && validation()) {

            verifyCode(binding.edOtp1.getText().toString() + "" + binding.edOtp2.getText().toString() + "" + binding.edOtp3.getText().toString() + "" + binding.edOtp4.getText().toString() + "" + binding.edOtp5.getText().toString() + "" + binding.edOtp6.getText().toString());


        }
    }

    private void createUser() {

        custPrograssbar.prograssCreate(this);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("name", user.getName());
            jsonObject.put("mobile", user.getMobile());
            jsonObject.put("ccode", user.getCcode());
            jsonObject.put("email", user.getEmail());
            jsonObject.put("password", user.getPassword());
            jsonObject.put("refercode", user.getRefercode());

        } catch (Exception e) {
            e.printStackTrace();
        }
        RequestBody bodyRequest = RequestBody.create(jsonObject.toString(), MediaType.parse("application/json"));
        Call<JsonObject> call = APIClient.getInterface().createUser(bodyRequest);
        GetResult getResult = new GetResult(this);
        getResult.setMyListener(this);
        getResult.callForLogin(call, "2");

    }

    @Override
    public void callback(JsonObject result, String callNo) {
        try {
            custPrograssbar.closePrograssBar();
            if (callNo.equalsIgnoreCase("2")) {
                Gson gson = new Gson();

                Login loginUser = gson.fromJson(result.toString(), Login.class);
                Toast.makeText(this, loginUser.getResponseMsg(), Toast.LENGTH_LONG).show();
                if (loginUser.getResult().equalsIgnoreCase("true")) {
                    sessionmanager.setBooleanData(login, true);
                    sessionmanager.setUserDetails(loginUser.getUserLogin());
                    OneSignal.sendTag(owneri, loginUser.getUserLogin().getId());

                    startActivity(new Intent(this, HomeActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
                }
            }else if (callNo.equalsIgnoreCase("1")) {
                Log.e("result", "-->" + result.toString());
                Gson gson = new Gson();
                RestResponse response = gson.fromJson(result.toString(), RestResponse.class);
                if (response.getResult().equalsIgnoreCase("true")) {
                    verificationOTP = response.getOtp();
                }

            }

        } catch (Exception e) {
            Log.e("Error", "--> " + e.getMessage());

        }
    }

    public boolean validation() {

        if (binding.edOtp1.getText().toString().isEmpty()) {
            binding.edOtp1.setError("");
            return false;
        }
        if (binding.edOtp2.getText().toString().isEmpty()) {
            binding.edOtp2.setError("");
            return false;
        }
        if (binding.edOtp3.getText().toString().isEmpty()) {
            binding.edOtp3.setError("");
            return false;
        }
        if (binding.edOtp4.getText().toString().isEmpty()) {
            binding.edOtp4.setError("");
            return false;
        }
        if (binding.edOtp5.getText().toString().isEmpty()) {
            binding.edOtp5.setError("");
            return false;
        }
        if (binding.edOtp6.getText().toString().isEmpty()) {
            binding.edOtp6.setError("");
            return false;
        }
        return true;
    }

}