package it.integry.integrywmsnative.core.expansion;

import android.app.Dialog;
import android.view.KeyEvent;

import androidx.appcompat.app.AppCompatActivity;

import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.core.utility.UtilityProgress;

public class BaseActivity extends AppCompatActivity {


    protected Dialog mCurrentProgress;

    public BaseActivity() {
        //Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this, BaseActivity.class));
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (BarcodeManager.isEnabled() && BarcodeManager.isKeyboardEmulator()) {
            if (event.getAction() == KeyEvent.ACTION_DOWN || event.getAction() == KeyEvent.ACTION_MULTIPLE && !isControlKey(event)) {
                return BarcodeManager.onKeyDown(event.getKeyCode(), event);
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private boolean isControlKey(KeyEvent keyEvent) {
        int keyCode = keyEvent.getKeyCode();
        return (
                keyCode == KeyEvent.KEYCODE_BACK ||
                        keyCode == KeyEvent.KEYCODE_SHIFT_LEFT ||
                        keyCode == KeyEvent.KEYCODE_DEL

        );
    }


    protected void openProgress() {
        runOnUiThread(() -> {
            BarcodeManager.disable();
            if (this.mCurrentProgress == null) {
                this.mCurrentProgress = UtilityProgress.createDefaultProgressDialog(this);
            }
        });
    }

    protected void closeProgress() {
        runOnUiThread(() -> {
            BarcodeManager.enable();
            if (mCurrentProgress != null) {
                mCurrentProgress.dismiss();
                mCurrentProgress = null;
            }
        });
    }


    public void onLoadingStarted() {
        new Thread(() -> {
            BarcodeManager.disable();
            this.openProgress();
        }).start();
    }

    public void onLoadingEnded() {
        new Thread(() -> {
            this.closeProgress();
            BarcodeManager.enable();
        }).start();
    }

    public void onError(Exception ex) {
        this.runOnUiThread(() -> {
            this.closeProgress();
            UtilityExceptions.defaultException(this, ex, mCurrentProgress);
            BarcodeManager.enable();
        });
    }
}
