package it.integry.integrywmsnative.core.expansion;

import android.os.Bundle;
import android.view.KeyEvent;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import javax.inject.Inject;

import it.integry.integrywmsnative.MainApplication;
import it.integry.integrywmsnative.core.barcode_reader.BarcodeManager;
import it.integry.integrywmsnative.core.utility.UtilityExceptions;
import it.integry.integrywmsnative.view.dialogs.DialogProgressView;

public class BaseActivity extends AppCompatActivity {

    @Inject
    public DialogProgressView mCurrentProgress;

    private boolean progressOpened;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        MainApplication.appComponent
                .baseActivityComponent()
                .create()
                .inject(this);
    }

    public void onLoadingStarted() {
        BarcodeManager.disable();
        this.openProgress();
    }

    public void onLoadingEnded() {
        this.closeProgress();
    }

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


    private void openProgress() {
        BarcodeManager.disable();
        if (!progressOpened && !this.mCurrentProgress.isAdded() && !this.mCurrentProgress.isInLayout()) {
            this.progressOpened = true;
            runOnUiThread(() -> {
                this.mCurrentProgress.show(getSupportFragmentManager(), "tag");
            });
        }
    }

    private void closeProgress() {
        BarcodeManager.enable();
        if (progressOpened) {
            this.progressOpened = false;
            runOnUiThread(() -> {
                mCurrentProgress.dismiss();
            });
        }
    }

    @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

        );
    }

}
