package demo.mapi.ccv.eu.mapi_demo.activities;

import android.os.Bundle;
import android.view.SurfaceView;

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

import demo.mapi.ccv.eu.mapi_demo.AndroidLogger;
import demo.mapi.ccv.eu.mapi_demo.R;
import eu.ccvlab.mapi.core.api.response.result.Error;
import eu.ccvlab.mapi.core.logging.MPALogging;
import eu.ccvlab.mapi.hardware.PaxService;
import eu.ccvlab.mapi.hardware.interfaces.barcodeScanner.BarcodeScannerDelegate;

public class BarcodeScannerActivity extends AppCompatActivity {

    SurfaceView surfaceView;

    private PaxService paxService;
    private AlertDialog resultDialog;
    private AndroidLogger androidLogger = new AndroidLogger("BarcodeScannerActivity");

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.barcodescanner_activity);
        surfaceView = findViewById(R.id.view_finder);
        MPALogging.addLogger(androidLogger);
    }

    @Override
    protected void onStart() {
        super.onStart();
        startScanner();
    }

    public void startScanner() {
        paxService = new PaxService();
        paxService.scanBarcode(surfaceView, new BarcodeScannerDelegate() {
            @Override
            public void onSuccess(String barcodeScannerResult) {
                if (isFinishing() || isDestroyed()) {
                    return;
                }
                runOnUiThread(() -> showResult(barcodeScannerResult));
            }

            @Override
            public void onError(Error error) {
                runOnUiThread(() -> showResult(error.mapiError().description()));
            }
        }, this);
    }

    @Override
    protected void onDestroy() {
        if(paxService != null){
            paxService.stopScanBarcode();
        }

        if (resultDialog != null && resultDialog.isShowing()) {
            resultDialog.dismiss();
            resultDialog = null;
        }

        MPALogging.removeLogger(androidLogger);

        super.onDestroy();
    }

    @Override
    protected void onPause() {
        if(paxService != null){
            paxService.stopScanBarcode();
        }
        super.onPause();
    }

    public void showResult(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setMessage(message)
                .setTitle("Scan result");

        builder.setPositiveButton("Ok", (dialog, id) -> {
            dialog.dismiss();
            onBackPressed();
        });

        resultDialog = builder.create();

        if (isFinishing() || isDestroyed()) {
            return;
        }
        resultDialog.show();
    }
}
