package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.google.gson.Gson;
import com.cygnusa.hyperm.pinview.PinView;
import com.cygnusa.hyperm.screenpinview.AppLockActivity;
import com.cygnusa.hyperm.screenpinview.ChangeAppLockActivity;
import com.cygnusa.hyperm.screenpinview.ForgotAppLockActivity;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.OtpResponse;
import com.cygnusa.hyperm.wrappers.UserResponse;

import java.io.File;
import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class OtpActivity extends AppCompatActivity {

    PinView pinview;
    public OtpResponse errorResponse = new OtpResponse();
    public UserResponse user = new UserResponse();
    TransparentProgressDialog progressDialog;
    ApiService restService;
    public int counter;
    TextView mobileNumTextView, resentOtpTxt, count_time;
    String type;

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    Objects.requireNonNull(activity.getCurrentFocus()).getWindowToken(), 0);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        restService = ((MainApplication) getApplication()).getClient();

        setContentView(R.layout.otp_activity);
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            type = extras.getString("type");

        }
        pinview = findViewById(R.id.pinView);
        count_time = findViewById(R.id.count_time);
        mobileNumTextView = findViewById(R.id.mobileNo);
        resentOtpTxt = findViewById(R.id.resentOtp);
        resentOtpTxt.setEnabled(false);
        resentOtpTxt.setAlpha(0.5f);
        resentOtpTxt.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        reSentOtp();
                    }
                });
        findViewById(R.id.btn_cancel).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (type.equalsIgnoreCase("forgot")) {
                            Intent i = new Intent(OtpActivity.this, AppLockActivity.class);
                            startActivity(i);
                            finish();
                        } else {
                            Intent result = new Intent();
                            setResult(Activity.RESULT_CANCELED, result);
                            finish();
                            OtpActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                    R.anim.animation_f_leave);
                        }

                    }
                });

        findViewById(R.id.btn_submit).setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (Objects.requireNonNull(pinview.getText()).toString().equalsIgnoreCase("")) {
                            GlobalData.showToast(getBaseContext(), "Please enter Valid OTP", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        otpValidation(pinview.getText().toString());

                    }
                });
        findViewById(R.id.bgLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(pinview.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        });
        sentOtp();
        setupWindowAnimations();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        Objects.requireNonNull(getSupportActionBar()).setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);
    }

    @SuppressLint("SetTextI18n")
    private void setData(String mobileNo, String otpexpirytime) {
        int millsec = Integer.parseInt(otpexpirytime) * 60 * 1000;
        new android.os.CountDownTimer(millsec, 1000) {
            public void onTick(long millisUntilFinished) {
                String formattedTime = String.format("%02d:%02d Sec",
                        TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) % TimeUnit.HOURS.toMinutes(1),
                        TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) % TimeUnit.MINUTES.toSeconds(1));
                count_time.setText(formattedTime);
                counter++;
            }

            @SuppressLint("SetTextI18n")
            public void onFinish() {
                count_time.setText("00:00");
                resentOtpTxt.setEnabled(true);
                resentOtpTxt.setAlpha(1f);
            }
        }.start();
        Paint p = new Paint();
        p.setColor(getResources().getColor(R.color.btn_bg_color));
        resentOtpTxt.setPaintFlags(resentOtpTxt.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        String alterStr = new StringBuilder(mobileNo).replace(2, 7, "XXXXX").toString();
        mobileNumTextView.setText("Your OTP has been sent to your " + alterStr);
    }

    public void sentOtp() {
        if (new UtilService().isNetworkAvailable(OtpActivity.this)) {
            progressDialog = new TransparentProgressDialog(OtpActivity.this);
            progressDialog.show();

            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("device_type", "android");
                restService.sentMPINOtp(map).enqueue(new Callback<OtpResponse>() {
                    @Override
                    public void onResponse(Call<OtpResponse> call, Response<OtpResponse> response) {
                        errorResponse = response.body();

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (errorResponse != null && errorResponse.getStatus() == 200) {
                            setData(GlobalData.user.getData().getMobileno(), errorResponse.getData().getOtp_expiry());
                        } else if (errorResponse != null) {
                            GlobalData.showToast(getBaseContext(), errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<OtpResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                GlobalData.showToast(getBaseContext(), "Server Error. Try again.", Toast.LENGTH_SHORT).show();
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }

                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    public void reSentOtp() {
        if (new UtilService().isNetworkAvailable(OtpActivity.this)) {
            progressDialog = new TransparentProgressDialog(OtpActivity.this);
            progressDialog.show();
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("device_type", "android");
                restService.sentMPINOtp(map).enqueue(new Callback<OtpResponse>() {
                    @Override
                    public void onResponse(Call<OtpResponse> call, Response<OtpResponse> response) {
                        errorResponse = response.body();
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (errorResponse != null && errorResponse.getStatus() == 200) {
                            setData(GlobalData.user.getData().getMobileno(), errorResponse.getData().getOtp_expiry());
                        } else if (errorResponse != null) {
                            GlobalData.showToast(getBaseContext(), errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        }


                    }

                    @Override
                    public void onFailure(Call<OtpResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }

    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(OtpActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void otpValidation(String otp) {

        boolean cancel = false;
        View focusView = null;
        if (Objects.requireNonNull(pinview.getText()).toString().length() < 4) {
            GlobalData.showToast(getBaseContext(), "please enter 4 digits", Toast.LENGTH_SHORT).show();
            focusView = pinview;
            cancel = true;
        }
        if (cancel) {
            focusView.requestFocus();
        } else {
            if (new UtilService().isNetworkAvailable(OtpActivity.this)) {
                progressDialog = new TransparentProgressDialog(OtpActivity.this);
                progressDialog.show();
                try {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("otp", otp);
                    map.put("type", "mpin");


                    restService.OtpValidation(map).enqueue(new Callback<UserResponse>() {
                        @Override
                        public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                            user = response.body();
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }

                            if (user != null && user.getStatus() == 200) {
                                getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                                        .edit().putString("FCM_TOKEN_ID", "").apply();
                                if (Build.VERSION.SDK_INT >= 23) {
                                    if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                            == PackageManager.PERMISSION_GRANTED) {
                                        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                                                + "/" + ".HYPERM", "PDF");
                                        if (f1.exists()) {
                                            f1.delete();
                                        }
                                    }
                                } else {
                                    File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                                            + "/" + ".HYPERM", "PDF");
                                    if (f1.exists()) {
                                        f1.delete();
                                    }
                                }
                                if (type.equalsIgnoreCase("change")) {
                                    Intent i = new Intent(OtpActivity.this, ChangeAppLockActivity.class);
                                    startActivity(i);
                                    finish();
                                } else if (type.equalsIgnoreCase("forgot")) {
                                    Intent i = new Intent(OtpActivity.this, ForgotAppLockActivity.class);
                                    startActivity(i);
                                    finish();
                                } else {
                                    Intent i = new Intent(OtpActivity.this, AppLockActivity.class);
                                    startActivity(i);
                                    finish();
                                }


                            } else if (user != null) {
                                GlobalData.showToast(getBaseContext(), user.getMessage(), Toast.LENGTH_SHORT).show();

                            } else if (response.body() != null && Objects.requireNonNull(response.body()).getStatus() == 401) {
                                GlobalData.canLogout = true;
                                new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                finish();
                            } else if (response.errorBody() != null) {
                                Gson gson = new Gson();
                                ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                                GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();


                                if (message.getStatus() == 401) {
                                    GlobalData.canLogout = true;
                                    new Handler(HomeActivity.callback).sendEmptyMessage(0);
                                    finish();
                                }


                            }


                        }

                        @Override
                        public void onFailure(Call<UserResponse> call, Throwable t) {
                            if (progressDialog != null && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
            }
        }

    }


    @Override
    public void onBackPressed() {

        if (type.equalsIgnoreCase("forgot")) {
            Intent i = new Intent(OtpActivity.this, AppLockActivity.class);
            startActivity(i);
            finish();
        } else {
            finish();
            OtpActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    protected void onResume() {
        super.onResume();

        if (GlobalData.canLogout) {
            finish();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {

            if (type.equalsIgnoreCase("forgot")) {
                Intent i = new Intent(OtpActivity.this, AppLockActivity.class);
                startActivity(i);
                finish();
            } else {
                finish();
                OtpActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                        R.anim.animation_f_leave);
            }

        }
        return super.onOptionsItemSelected(item);
    }

}
