package com.app.simplitend.welcome.welcomecg.fragments;

import static androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.biometric.BiometricManager;
import androidx.biometric.BiometricPrompt;
import androidx.core.content.ContextCompat;

import com.app.simplitend.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
import com.app.simplitend.apputils.AppUtil;
import com.app.simplitend.caregiverdashboard.activities.CaregiverDashActivity;
import com.app.simplitend.databinding.CgAuthFragmentBinding;

public class CgAuthActivity extends AppCompatActivity {

    protected CgAuthFragmentBinding binding;

    private BiometricManager biometricManager;
    private BiometricPrompt biometricPrompt;

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

        int cg_security = AppUtil.getWantSecurityFlag(this);

        if (cg_security == AppUtil.NOT_ASKED_CG_SECURITY) {
            // user has never been asked to setup security
            // thus, showing that ui
            binding.notAsked.setVisibility(View.VISIBLE);
            binding.askedView.setVisibility(View.GONE);
        } else {
            // user was asked already
            binding.notAsked.setVisibility(View.GONE);
            binding.askedView.setVisibility(View.VISIBLE);
        }

        initViews();

        clickEvents();

    }

    @Override
    protected void attachBaseContext(Context newBase) {
        final Configuration configuration = new Configuration(newBase.getResources().getConfiguration());
        configuration.fontScale = Math.min(configuration.fontScale, 1.1f);
        applyOverrideConfiguration(configuration);
        super.attachBaseContext(newBase);
    }

    private void clickEvents() {
        binding.fingerprintView.setOnClickListener(v -> {
            authenticateBiometrics();
        });

        binding.setUpFingerprint.setOnClickListener(v -> {
            authenticateBiometrics();
        });

        binding.skip.setOnClickListener(v -> {
            AppUtil.setWantSecurityFlag(this, AppUtil.CG_NO_SECURITY_NEEDED);
            if (!AppUtil.isRegistrationComplete(CgAuthActivity.this)){
                // USER IS IN THE REGISTRATION PROCESS
                // show thank you page
                showThankYouScreen();
            }else {
                gotoCgDash();
            }
        });

        binding.proceed.setOnClickListener(v -> {
            gotoCgDash();
        });

    }

    private void showThankYouScreen() {
        AppUtil.setCgRegistrationComplete(this, true);

        binding.connectCompleteView.setVisibility(View.VISIBLE);
        binding.askedView.setVisibility(View.GONE);
        binding.fingerprintView.setVisibility(View.GONE);

        Glide.with(this)
                .asGif()
                .load(R.raw.done_anim_primary)
                .listener(new RequestListener<GifDrawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                        resource.setLoopCount(1);
                        return false;
                    }
                })
                .into(binding.animIv);
    }

    private void initViews() {

        biometricManager = BiometricManager.from(this);

        biometricPrompt = new BiometricPrompt(this, ContextCompat.getMainExecutor(this),
                new BiometricPrompt.AuthenticationCallback() {
                    @Override
                    public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) {
                        super.onAuthenticationError(errorCode, errString);
                    }

                    @Override
                    public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) {
                        super.onAuthenticationSucceeded(result);
                        AppUtil.setWantSecurityFlag(CgAuthActivity.this, AppUtil.CG_SECURITY_NEEDED);
                        if (!AppUtil.isRegistrationComplete(CgAuthActivity.this)){
                            // USER IS IN THE REGISTRATION PROCESS
                            // show thank you page
                            showThankYouScreen();
                        }else {
                            gotoCgDash();
                        }
                    }

                    @Override
                    public void onAuthenticationFailed() {
                        super.onAuthenticationFailed();
                    }
                });

        configureBiometrics();

        // four digit pin catch
        binding.pin.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }

    private void authenticateBiometrics() {
        if (biometricManager == null) return;

        int biometric_status = biometricManager.canAuthenticate(BIOMETRIC_STRONG);

        if (biometric_status == BiometricManager.BIOMETRIC_SUCCESS) {
            // go ahead and do it.
            biometricPrompt.authenticate(new BiometricPrompt.PromptInfo.Builder()
                    .setTitle("Scan your fingerprint to unlock SimpliTend")
                    .setConfirmationRequired(false)
                    .setDescription("User your device's fingerprint sensor")
                    .setNegativeButtonText("Cancel")
                    .build());
        } else if (biometric_status == BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED) {
            // no fingerprints enrolled

            AppUtil.showAlert(this,
                    "No biometrics added.",
                    "No fingerprints are registered on your device.\nKindly add biometrics to authenticate.",
                    "Go to settings",
                    ((dialogInterface, i) -> {

                        final Intent enrollIntent;
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                            enrollIntent = new Intent(Settings.ACTION_BIOMETRIC_ENROLL);
                            enrollIntent.putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, BIOMETRIC_STRONG);
                        } else {
                            enrollIntent = new Intent(Settings.ACTION_SECURITY_SETTINGS);
                        }

                        startActivity(enrollIntent);

                    }),
                    "No thanks",
                    ((dialogInterface, i) -> {
                    }));

        }

    }

    public void configureBiometrics() {

        if (biometricManager == null) return;

        switch (biometricManager.canAuthenticate(BIOMETRIC_STRONG)) {
            case BiometricManager.BIOMETRIC_ERROR_NO_HARDWARE:
            case BiometricManager.BIOMETRIC_ERROR_HW_UNAVAILABLE:
                binding.fingerprintOr.setVisibility(View.GONE);
                binding.fingerprintView.setVisibility(View.GONE);
                // no fingerprint sensor or some error occurred thus, skipping this screen
                gotoCgDash();
                break;
            case BiometricManager.BIOMETRIC_SUCCESS:
            case BiometricManager.BIOMETRIC_ERROR_NONE_ENROLLED:
                binding.fingerprintView.setVisibility(View.VISIBLE);
                break;
        }
    }

    private void gotoCgDash() {
        Intent intent = new Intent(CgAuthActivity.this, CaregiverDashActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        startActivity(intent);
        CgAuthActivity.this.finish();
    }
}
