package my.com.pcloud.salesapplite;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;


public class camera extends Activity {





    Camera mCamera;
    CameraPreview mPreview;
    Handler autoFocusHandler;


    TextView textView_scan_instruction;


    ImageScanner scanner;

    FrameLayout preview;


    boolean previewing= false;


    String scanned_code="";
    String this_amount="";


    String scan_action_mode="";



    String sender_id = "";
    String sender_name = "";
    String sender_full_name = "";


    String scan_title="";



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


        setContentView(R.layout.camera);


        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        mToolbar.setTitle(getString(R.string.scanner));
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        mToolbar.setTitleTextColor(Color.WHITE);


        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });





        textView_scan_instruction = findViewById(R.id.textView_scan_instruction);
        preview = (FrameLayout) findViewById(R.id.cameraPreview);




        Bundle extras = getIntent().getExtras();
        if(extras == null) {

        } else {

            scan_title = extras.getString("TITLE");
            scan_action_mode = extras.getString("MODE");
            textView_scan_instruction.setText(extras.getString("INSTRUCTION"));


            mToolbar.setTitle(scan_title);

        }









        int MyVersion = Build.VERSION.SDK_INT;
        if (MyVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
            if (!checkIfAlreadyhavePermission()) {
                requestForSpecificPermission();
            }
            else
            {
                setup_camera();

            }
        }
        else
        {

            setup_camera();
        }







    }





    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean checkIfAlreadyhavePermission() {

        if(this.checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
        {
            return true;
        }
        else
        {

            return false;
        }

    }





    @TargetApi(Build.VERSION_CODES.M)
    private void requestForSpecificPermission() {


        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, 101);


    }


    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 1: {



                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    setup_camera();


                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    Toast.makeText(this, "Permission denied. Cammera cannot be open", Toast.LENGTH_SHORT).show();



                    Intent returnIntent = new Intent();
                    setResult(Activity.RESULT_CANCELED, returnIntent);


                    finish();




                }
                return;
            }

        }
    }




    @Override
    public void onBackPressed() {

        super.onBackPressed();


        Intent returnIntent = new Intent();
        setResult(Activity.RESULT_CANCELED, returnIntent);


        finish();

    }


    @Override
    public void onDestroy() {
        super.onDestroy();

        releaseCamera();


    }

    public void setup_camera()
    {


        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);

        preview.addView(mPreview);


        //activate scanning camera:

        mCamera.setPreviewCallback(previewCb);
        mCamera.startPreview();
        previewing = true;
        //mCamera.autoFocus(autoFocusCB);




    }




















    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
        public void run() {
            if (previewing)
                mCamera.autoFocus(autoFocusCB);
        }
    };

    Camera.PreviewCallback previewCb = new Camera.PreviewCallback() {
        public void onPreviewFrame(byte[] data, Camera camera) {


            try{

                Camera.Parameters parameters = camera.getParameters();
                Camera.Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);

                if (result != 0) {
                    previewing = false;
                    mCamera.setPreviewCallback(null);
                    mCamera.stopPreview();

                    SymbolSet syms = scanner.getResults();
                    for (Symbol sym : syms) {



                        //scanText.setText("" + sym.getData());
                        //display_compound(sym.getData());


                        releaseCamera();

                        //scan_check_product(sym.getData());

                        scanned_code = sym.getData();




                        if(scan_action_mode.equals("PURCHASE_PRODUCT"))
                        {



                            Intent returnIntent = new Intent();
                            returnIntent.putExtra("scanned_code",scanned_code);
                            setResult(Activity.RESULT_OK,returnIntent);
                            finish();



                        }



                        if(scan_action_mode.equals("PURCHASE"))
                        {



                            Intent returnIntent = new Intent();
                            returnIntent.putExtra("scanned_code",scanned_code);
                            setResult(Activity.RESULT_OK,returnIntent);
                            finish();



                        }
                        if(scan_action_mode.equals("USE"))
                        {

                            Intent returnIntent = new Intent();
                            returnIntent.putExtra("scanned_code",scanned_code);
                            setResult(Activity.RESULT_OK,returnIntent);
                            finish();



                        }



                    }
                }

            } catch (Exception e)
            {




            }

        }
    };

    // Mimic continuous auto-focusing
    Camera.AutoFocusCallback autoFocusCB = new Camera.AutoFocusCallback() {
        public void onAutoFocus(boolean success, Camera camera) {
            autoFocusHandler.postDelayed(doAutoFocus, 1000);
        }
    };











}
