package com.reactlibrary.vishwamdkyclib.Activities;

/*
 * Vishwam Corp CONFIDENTIAL

 * Vishwam Corp 2018
 * All Rights Reserved.

 * NOTICE:  All information contained herein is, and remains
 * the property of Vishwam Corp. The intellectual and technical concepts contained
 * herein are proprietary to Vishwam Corp
 * and are protected by trade secret or copyright law of U.S.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Vishwam Corp
 */

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.face.Face;
import com.google.android.gms.vision.face.FaceDetector;
import com.microsoft.appcenter.AppCenter;
import com.microsoft.appcenter.analytics.Analytics;
import com.microsoft.appcenter.crashes.Crashes;
import com.reactlibrary.R;
import com.reactlibrary.vishwamdkyclib.Camera.CameraSource;
import com.reactlibrary.vishwamdkyclib.Camera.CameraSourcePreview;
import com.reactlibrary.vishwamdkyclib.DocCaptureCompleteHandler;
import com.reactlibrary.vishwamdkyclib.FrontalAadhar;
import com.reactlibrary.vishwamdkyclib.ImageAnalysis.AadhaarAnalysis;
import com.reactlibrary.vishwamdkyclib.LibUtils;
import com.reactlibrary.vishwamdkyclib.LiveFaceAuthHolder;
import com.reactlibrary.vishwamdkyclib.RearAadhar;
import com.reactlibrary.vishwamdkyclib.Tracker.DocRectangleView;
import com.reactlibrary.vishwamdkyclib.Tracker.FaceDect;
import com.reactlibrary.vishwamdkyclib.Tracker.GraphicOverlay;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.reactlibrary.vishwamdkyclib.Activities.VishwamFaceActivity.circleX;
import static com.reactlibrary.vishwamdkyclib.Activities.VishwamFaceActivity.circleY;
import static com.reactlibrary.vishwamdkyclib.Camera.CameraSource.needAnalysis;
import static com.reactlibrary.vishwamdkyclib.Camera.CameraSource.takePicture;
import static com.reactlibrary.vishwamdkyclib.ImageAnalysis.AadhaarAnalysis.okForDocAnalysis;
import static com.reactlibrary.vishwamdkyclib.ImageAnalysis.AadhaarAnalysis.readyForDocAnalysis;
import static com.reactlibrary.vishwamdkyclib.LibConstants.IS_DOC_CONTEXT;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.docfaceCoordinates;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.frontJSON;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.isBack;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.isFront;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.ocrBackBlock;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.ocrBackPlots;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.ocrFrontPlots;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.path224llll;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.pathHalfDoc;
import static com.reactlibrary.vishwamdkyclib.Networking.VishwamNetworkHelper.rearJSON;
import static com.reactlibrary.vishwamdkyclib.Tracker.FaceDect.previewFaceDetector;
import static com.reactlibrary.vishwamdkyclib.Tracker.FaceGraphic.docOrNot;
import static com.reactlibrary.vishwamdkyclib.Tracker.FaceGraphic.faceCoordinatesBackupInt;
import static com.reactlibrary.vishwamdkyclib.Tracker.FaceGraphic.mHintOutlinePaint;

//import static com.vishwam.vishwamdkyclib.ImageAnalysis.AadhaarAnalysis.canAddDocData;

/**
 * Here in this activity we render preview on surfaceview capture image onclick process it.
 * **/

public class VishwamDocActivity extends AppCompatActivity implements FaceDect.OnMultipleFacesDetectedListener, FaceDect.OnCaptureListener, View.OnClickListener, SensorEventListener {

    private Context context;
    FaceDect faceDect;
    public CameraSource mCameraSource;
    private CameraSourcePreview mPreview;
    private GraphicOverlay mGraphicOverlay;
    private boolean wasActivityResumed = false;
    ImageView previewImages;
    public ProgressDialog dialog;
    String pathDoc, path224;
    LibUtils libUtils;
    public static Bitmap squareBitmapDoc;
    public boolean previewOrNot, okForCapture = true;
    public JSONObject afterDocCaptured;
    public static boolean frontOrNot;

    public Button exitBtn, docCaptureBtn;

    FrontalAadhar frontalAadhar;
    RearAadhar rearAadhar;
    public static String s;
    SensorManager sensorManager;
    Sensor rotationVectorSensor;
    boolean allowTilt = true, shouldSetPadding = false, allowDataLogging;
    int roll = 10, pitch = 10;
    double padding = 0.05;
    int currentScreenW, currentScreenH, currentImageWidth, currentImageHeight;
    String docCapturePrompt;
    Bitmap halfDocBitmap, docBitmap224;
    TextView docInstructionTextview;
    public static  boolean doSuccessLogs;

    public static AadhaarAnalysis aadhaarAnalysis;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_capture);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        initAnalytics();
        doSuccessLogs = true;
        docOrNot = true;
        ocrBackPlots = "";
        ocrFrontPlots = "";
        faceCoordinatesBackupInt = null;

        afterDocCaptured = new JSONObject();
        frontalAadhar = new FrontalAadhar(this);
        rearAadhar = new RearAadhar(this);

        needAnalysis = true;

//        framesAddedCount = 0;

        if (!readyForDocAnalysis) {
            aadhaarAnalysis = new AadhaarAnalysis(getAssets(), VishwamDocActivity.this);
            aadhaarAnalysis.initAadhaarAnalysis();
        }

        aadhaarAnalysis.setupAadhaarAnalysis();

        faceFramedetector = new FaceDetector.Builder(VishwamDocActivity.this)
                .setTrackingEnabled(false)
                .setLandmarkType(FaceDetector.ALL_LANDMARKS)
                .build();

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        currentScreenH = metrics.heightPixels;
        currentScreenW = metrics.widthPixels;
        //Log.e("vishwamSukshiSW&H", currentScreenW + "," + currentScreenH);

        circleX = currentScreenW / 2;
        circleY = currentScreenH / 2;

        RelativeLayout relativeLayout = findViewById(R.id.myRelativeLayout);
        docCaptureBtn = findViewById(R.id.buttonDoc);
        libUtils = new LibUtils();

        Resources resources = this.getResources();
        context = getApplicationContext();
        dialog = new ProgressDialog(VishwamDocActivity.this);

        exitBtn = findViewById(R.id.exitBtn);

        Intent i = getIntent();
        Bundle extras = i.getExtras();

        if (extras != null) {
            previewOrNot = extras.getBoolean("shouldShowReviewScreen");
            frontOrNot = extras.getBoolean("front_view");
            allowTilt = extras.getBoolean("shouldAllowPhoneTilt");
            pitch = extras.getInt("allowedTiltPitch");
            roll = extras.getInt("allowedTiltRoll");
            padding = extras.getDouble("padding");
            shouldSetPadding = extras.getBoolean("shouldSetPadding");
            docCapturePrompt = extras.getString("docCapturePrompt");
            allowDataLogging = extras.getBoolean("allowDataLogging");
            //Log.e("shouldSetPaddingFromExt", String.valueOf(shouldSetPadding));
            //Log.e("paddingFromExtras", String.valueOf(padding));//docCapturePrompt
            if (!shouldSetPadding) {
                padding = 0;
            }
            DocRectangleView docRectangleView = new DocRectangleView(VishwamDocActivity.this, padding);
            relativeLayout.addView(docRectangleView);

            TextView titleView = new TextView(this);
            RelativeLayout.LayoutParams titleViewParams = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            titleViewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            titleViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
            titleViewParams.setMargins(40, 80, 40, 0);
            titleView.setLayoutParams(titleViewParams);
            titleView.setTextColor(getResources().getColor(R.color.colorTitle));
            titleView.setTextSize(18);
            titleView.setText(getString(R.string.document_capture));
            titleView.setBackgroundColor(getResources().getColor(R.color.white));
            relativeLayout.addView(titleView);

            docInstructionTextview = new TextView(this);
            RelativeLayout.LayoutParams docInstructionTextviewParams = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            docInstructionTextviewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            docInstructionTextviewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
            docInstructionTextviewParams.setMargins(40, (int) (currentScreenW * 2 / 3 + currentScreenW / 2.9f), 40, 0);
            docInstructionTextview.setLayoutParams(docInstructionTextviewParams);
            docInstructionTextview.setTextColor(getResources().getColor(R.color.colorTitle));
            docInstructionTextview.setTextSize(18);
            docInstructionTextview.setGravity(Gravity.CENTER);
            docInstructionTextview.setText(getString(R.string.doc_instruction));
            docInstructionTextview.setBackgroundColor(getResources().getColor(R.color.white));
            relativeLayout.addView(docInstructionTextview);

            TextView docPromptTextview = new TextView(this);
            RelativeLayout.LayoutParams ddocPromptTextviewParams = new RelativeLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            ddocPromptTextviewParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            ddocPromptTextviewParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
            ddocPromptTextviewParams.setMargins(40, (currentScreenW * 2 / 3 + currentScreenW / 5), 40, 0);
            docPromptTextview.setLayoutParams(ddocPromptTextviewParams);
            docPromptTextview.setTextColor(getResources().getColor(R.color.white));
            docPromptTextview.setTextSize(18);
            docPromptTextview.setGravity(Gravity.CENTER);
            docPromptTextview.setText(docCapturePrompt);
            docPromptTextview.setBackgroundColor(getResources().getColor(R.color.clear));
            relativeLayout.addView(docPromptTextview);

        } else {
            try {
                throw new Exception("please specify preview in Intent");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (frontOrNot) {
            docfaceCoordinates = "";
            //File folder = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), ".DKYC_Libr");
            File folder = new File(context.getFilesDir(), "DKYC_ReactLibr");

            if (folder.exists()) {
                for (File file : folder.listFiles()) {
                    file.delete();
                }
                folder.delete();
            }
        }
        sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
        rotationVectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);

        previewImages = findViewById(R.id.previewDocImage1);
        previewImages.setVisibility(View.GONE);
        mPreview = findViewById(R.id.previewDoc);
        mGraphicOverlay = findViewById(R.id.faceOverlayDoc);
        createCameraSourceFront();
        startCameraSource();

        mHintOutlinePaint = new Paint();
        mHintOutlinePaint.setColor(resources.getColor(R.color.green_color));
        mHintOutlinePaint.setStyle(Paint.Style.STROKE);
        mHintOutlinePaint.setStrokeWidth(resources.getDimension(R.dimen.hintStroke));

        docCaptureBtn.setOnClickListener(this);
        exitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


    }

    public void initAnalytics(){
        AppCenter.start(getApplication(), "edae2aab-a04a-49cd-8c64-ae5872a61a44", Analytics.class, Crashes.class);
        Analytics.setEnabled(true);
    }

    /**
     * Static method to start self activity passing parameters like DocCaptureCompleteListener.
     * **/
    public static void start(Context context, JSONObject docParams, DocCaptureCompleteHandler onDocCaptured) {
        logDocCaptureStartEvent(frontOrNot);
        Intent intent = new Intent(context, VishwamDocActivity.class);
        try {
            intent.putExtra("document", docParams.getString("document"));
            intent.putExtra("front_view", docParams.getBoolean("front_view"));

            if (docParams.has("shouldShowReviewScreen")) {
                intent.putExtra("shouldShowReviewScreen", docParams.getBoolean("shouldShowReviewScreen"));
            } else {
                intent.putExtra("shouldShowReviewScreen", true);
            }

            if (docParams.has("allowDataLogging")) {
                intent.putExtra("allowDataLogging", docParams.getBoolean("allowDataLogging"));
            } else {
                intent.putExtra("allowDataLogging", false);
            }

            if (docParams.has("shouldAllowPhoneTilt")) {
                intent.putExtra("shouldAllowPhoneTilt", docParams.getBoolean("shouldAllowPhoneTilt"));
            } else {
                intent.putExtra("shouldAllowPhoneTilt", true);
            }

            if (docParams.has("allowedTiltRoll")) {
                intent.putExtra("allowedTiltRoll", docParams.getInt("allowedTiltRoll"));
            } else {
                intent.putExtra("allowedTiltRoll", 10);
            }

            if (docParams.has("allowedTiltPitch")) {
                intent.putExtra("allowedTiltPitch", docParams.getInt("allowedTiltPitch"));
            } else {
                intent.putExtra("allowedTiltPitch", 10);
            }

            if (docParams.has("padding")) {
                intent.putExtra("padding", docParams.getDouble("padding"));
            } else {
                intent.putExtra("padding", 0.05);
            }


            if (docParams.has("shouldSetPadding")) {
                intent.putExtra("shouldSetPadding", docParams.getBoolean("shouldSetPadding"));
            } else {
                intent.putExtra("shouldSetPadding", false);
            }

            if (docParams.has("docCapturePrompt")) {
                intent.putExtra("docCapturePrompt", docParams.getString("docCapturePrompt"));
            } else {
                intent.putExtra("docCapturePrompt", "Document");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        LiveFaceAuthHolder.getInstance().setDocCaptureResultListener(onDocCaptured);
    }
    /**
     * Method for logging aws events on start of doc capture intent.
     * **/
    public static void logDocCaptureStartEvent(Boolean isFront) {
        if(doSuccessLogs){
            Map<String, String> properties = new HashMap<>();
            if (isFront) {
                properties.put("DocType", "Front");
            } else {
                properties.put("DocType", "Back");
            }
            Analytics.trackEvent("OnStartDocCapture", properties);
        }


    }

    ///////////////////////////////////////////////////// Gyroscope start ///////////////////////////////////////////////////////////
    /**
     * This method is invoked on gyroscope sensor change event thus by handling horizontal position of mobile.
     * **/
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onSensorChanged(SensorEvent event) {

        if (allowTilt) {
            docCaptureBtn.setOnClickListener(this);
            docCaptureBtn.setBackground(getResources().getDrawable(R.drawable.enable_camera));
        } else {
            float[] rotationMatrix = new float[16];
            SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values);
            float[] remappedRotationMatrix = new float[16];
            SensorManager.remapCoordinateSystem(rotationMatrix, SensorManager.AXIS_X, SensorManager.AXIS_Z, remappedRotationMatrix);
            float[] orientations = new float[3];
            SensorManager.getOrientation(remappedRotationMatrix, orientations);
            for (int i = 0; i < 3; i++) {
                orientations[i] = (float) (Math.toDegrees(orientations[i]));
            }
            if (orientations[1] > 90 - pitch && orientations[1] < 90 + pitch) {
                docCaptureBtn.setOnClickListener(this);
                docCaptureBtn.setBackground(getResources().getDrawable(R.drawable.enable_camera));
                docInstructionTextview.setTextColor(getResources().getColor(R.color.colorTitle));
                docInstructionTextview.setText(getString(R.string.doc_instruction));
            } else {
                docCaptureBtn.setOnClickListener(null);
                docCaptureBtn.setBackground(getResources().getDrawable(R.drawable.disable_camera));
                docInstructionTextview.setTextColor(getResources().getColor(R.color.red_color));
                docInstructionTextview.setText(getString(R.string.doc_instruction_red));
            }
        }
    }
    /**
     * Method to get availability of gyroscope on phone.
     * **/
    public boolean isGyroscopeAvailable() {
        PackageManager packageManager = getPackageManager();
        return packageManager.hasSystemFeature(PackageManager.FEATURE_SENSOR_GYROSCOPE);
    }
    /***
     * This is method is invoked on gyrocope accuracy change.
     * **/
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
    /**
     * This method is invoked by system on start of activity and here we are registering the gyroscope.
     * **/
    @Override
    protected void onStart() {
        super.onStart();
        if (isGyroscopeAvailable()) {
            sensorManager.registerListener(this, rotationVectorSensor, SensorManager.SENSOR_DELAY_NORMAL);
        }
    }
    /**
     * This method is invoked by system on activity close and here we ae de-registering the gyroscope.
     * **/
    @Override
    protected void onStop() {
        super.onStop();
        if (isGyroscopeAvailable()) {
            sensorManager.unregisterListener(this);
        }
    }

    ///////////////////////////////////////////////////// Gyroscope end ///////////////////////////////////////////////////////////

    @Override
    public void onMultipleFacesDetected(int n) {}

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.buttonDoc) {

            okForDocAnalysis = false;
            if (okForCapture) {
                okForCapture = false;
                takePicture = true;
                //takePicture();
            }
        }
    }

    /**
     * This method invoked by camerasource class onfirst availability of frame and onclick of button.
     * **/

    @Override
    public void onCapture(byte[] data, int angle) {

        dialog.setMessage("Receiving Image...");
        dialog.setCancelable(false);
        dialog.show();

        stopCameraSource();

       /* if (frontOrNot){
            String obdAadhaar= aadhaarAnalysis.getAadhaarIndex();
            Log.e("vishwamOBDFront1", obdAadhaar);
        }else {
            String obdAadhaar= aadhaarAnalysis.getAadhaarIndex();
            Log.e("vishwamOBDBack1", obdAadhaar);
        }*/


        Bitmap OriginalBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);

        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        Bitmap rotatedbitmap = Bitmap.createBitmap(OriginalBitmap, 0, 0, OriginalBitmap.getWidth(), OriginalBitmap.getHeight(), matrix, true);
        currentImageWidth = rotatedbitmap.getWidth();
        currentImageHeight = rotatedbitmap.getHeight();
        //Log.e("vishwamSukshiIW&H", rotatedbitmap.getWidth() + ", " + rotatedbitmap.getHeight());
        //Log.e("vishwamSukshiSW&H", currentScreenW + "," + currentScreenH);
        squareBitmapDoc = libUtils.getDocBitmap(rotatedbitmap, padding);
        docBitmap224 = libUtils.get224Bitmap(squareBitmapDoc);
        //squareBitmapDocCompressed = libUtils.getDocCompressedBitmap(squareBitmapDoc);
        if (frontOrNot){
            halfDocBitmap = libUtils.getHalfBitmap(squareBitmapDoc);
        }

        isFront = false;
        isBack = false;
        ocrBackBlock = "";
        logDocPictureTakenEvent(frontOrNot);


        if (frontOrNot) {

            frontJSON = frontalAadhar.inspectFromBitmap(squareBitmapDoc);
            if (frontJSON != null) {
                s = String.valueOf(frontJSON);
                //Log.e("frontJson", frontJSON.toString());
            } else s = "";

            if (faceFramedetector.isOperational()) {
                new getFaceCs().execute();
            }

            if (previewOrNot) {
                moveToPreview();
            } else {
//                saveHalfDoc(halfDocBitmap);
                saveFile(squareBitmapDoc);
            }

        } else {

            rearJSON = rearAadhar.inspectFromBitmap(squareBitmapDoc);
            if (rearJSON != null) {
                s = String.valueOf(rearJSON);
                //Log.e("rearJson", rearJSON.toString());
            } else {
                s = "";
            }

            if (previewOrNot) {
                moveToPreview();
            } else {
//                saveHalfDoc(halfDocBitmap);
                saveFile(squareBitmapDoc);
            }
        }
    }
    /**
     * method to log event onPictureTaken.
     * **/

    public void logDocPictureTakenEvent(Boolean isFront) {
        if(doSuccessLogs){
            Map<String, String> properties = new HashMap<>();
            if (isFront) {
                properties.put("DocType","Front");
            } else {
                properties.put("DocType","Back");
            }

            Analytics.trackEvent("OnDocPictureTaken", properties);
        }
    }
    /**
     * Mehtod to log onOpenPreview.
     * **/
    public void logOnOpenPreview(boolean isFront) {
        if(doSuccessLogs){
            Map<String, String> properties = new HashMap<>();
            if (isFront) {
                properties.put("DocType","Front");
            } else {
                properties.put("DocType","Back");
            }

            Analytics.trackEvent("OnPreviewDoc", properties);
        }
    }



    /**
     * Method to move to preview activity just to confirm image from users.
     * **/

    public void moveToPreview() {
        logOnOpenPreview(frontOrNot);
        Intent intent = new Intent(VishwamDocActivity.this, PreviewActivity.class);
        intent.putExtra(IS_DOC_CONTEXT, 0);
        startActivityForResult(intent, 200);
        overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);


    }

    /**
     * This method is invoked by the system when acitivy passes on result to this activity.
     * **/
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200) {
            switch (resultCode) {
                case RESULT_OK:
                    okForStartCam = false;
                    dialog.show();
//                    saveHalfDoc(halfDocBitmap);
                    saveFile(squareBitmapDoc);
                    break;

                case RESULT_CANCELED:
                    aadhaarAnalysis.setupAadhaarAnalysis();
                    okForStartCam = true;
                    okForCapture = true;
                    if (frontOrNot){
                        docfaceCoordinates = "";
                        faceCoordinatesBackupInt = null;
                    }
                    dialog.dismiss();
                    Toast.makeText(this, "Photo rejected. Please retake picture", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }
    /**
     * Mehtod to save half doc for better image recognition for models and save it to local internal storage.
     * **/
    public void saveHalfDoc(Bitmap bitmap) {

        File file = libUtils.getOutputMediaFile(VishwamDocActivity.this, "DocHalf");
        if (frontOrNot) {
            pathHalfDoc = file.getPath();
        }
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();

                    save224(docBitmap224);
//                    saveFile(squareBitmapDoc);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * Method to save file to local internal storage.
     * **/
    public void saveFile(Bitmap bitmap) {

        File file = libUtils.getOutputMediaFile(VishwamDocActivity.this, "DocFull");
        pathDoc = file.getPath();
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();

                    if (frontOrNot){
                        saveHalfDoc(halfDocBitmap);
                    }else {
                        save224(docBitmap224);
                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * Method to save file with 224 size of image analysis.
     * **/
    public void save224(Bitmap bitmap) {

        File file = libUtils.getOutputMediaFile(VishwamDocActivity.this, "Doc224");
        path224 = file.getPath();
        path224llll = path224;
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 95, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();

                    afterSaving();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * Method to hold instance of docCaptureHandler on completion of activity.
     * **/
    public void afterSaving() {

        try {
            if (frontOrNot) {
                afterDocCaptured.put("imageUri", pathDoc);
            } else afterDocCaptured.put("imageUri", pathDoc);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        dialog.dismiss();
        logDocCaptureComplete(frontOrNot);
        LiveFaceAuthHolder.getInstance().getDocCaptureResultListener().onResult(null, afterDocCaptured);
        finish();
    }
    /**
     * Method to log CaptureComplete.
     * **/
    public void logDocCaptureComplete(Boolean isFront) {
        if(doSuccessLogs){
            Map<String, String> properties = new HashMap<>();
            if (isFront) {
                properties.put("DocType", "Front");
            } else {
                properties.put("DocType", "Back");
            }
            Analytics.trackEvent("OnCompleteDocCapture", properties);
        }


    }
    /**
     * Class to create thread to get face coordinates.
     * **/
    @SuppressLint("StaticFieldLeak")
    public class getFaceCs extends AsyncTask<String, String, Void> {

        @Override
        protected Void doInBackground(String... strings) {

            docfaceCoordinates = getFaceCoordinates(halfDocBitmap);
//            Log.e("vishwamSukshiCoordsDoc", docfaceCoordinates);
            return null;
        }
    }

    FaceDetector faceFramedetector;

    public String getFaceCoordinates(Bitmap bitmap) {

        Frame frame = new Frame.Builder().setBitmap(bitmap).build();
        SparseArray<Face> faces = faceFramedetector.detect(frame);

        if (faces.size() == 1) {
            Face face = faces.valueAt(0);

            float faceX = face.getPosition().x;
            float faceY = face.getPosition().y;
            float faceWidth = face.getWidth();
            float faceHeight = face.getHeight();
//            Log.e("vishwamSukshiXYWH", faceX + ", " + faceY + ", " + faceWidth + ", " +faceHeight);

            JSONObject faceCoordinates = new JSONObject();
            try {
                faceCoordinates.put("left", faceX);
                faceCoordinates.put("right", faceX + faceWidth);
                faceCoordinates.put("top", faceY);
                faceCoordinates.put("bottom", faceY + faceHeight);
                faceCoordinates.put("last", 1);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //Log.e("coordinatesImage", faceCoordinates.toString());
            return faceCoordinates.toString();
        } else if (faces.size() == 0) {
            JSONObject faceCoordinatesBackup = new JSONObject();

            if (faceCoordinatesBackupInt != null) {
                try {

                    float ratio1 = (float) currentImageHeight/currentImageWidth;
//                    Log.e("vishwamSukshiRatio1", String.valueOf(ratio1));
                    //float ratio2 = (float)

                    float cardW = (float) currentImageWidth * 9 / 10;
                    float cardH = cardW / 1.45f;

                    float topFG = (faceCoordinatesBackupInt.getInt("top"));
                    float bottomFG = (faceCoordinatesBackupInt.getInt("bottom"));
                    float leftFG = (faceCoordinatesBackupInt.getInt("left"));
                    float rightFG = (faceCoordinatesBackupInt.getInt("right"));

                    float topI = (topFG * currentImageWidth) / currentScreenW;
                    float bottomI = (bottomFG * currentImageWidth) / currentScreenW;
                    float leftI = (leftFG * currentImageWidth) / currentScreenW;
                    float rightI = (rightFG * currentImageWidth) / currentScreenW;

                    float topC = topI - ((currentImageHeight - cardH)/2) - (cardH/10);
                    float bottomC = bottomI - ((currentImageHeight - cardH)/2) - (cardH/10);
                    float leftC = leftI - ((currentImageWidth - cardW)/2);
                    float rightC = rightI - ((currentImageWidth - cardW)/2);

                    faceCoordinatesBackup.put("left", leftC);
                    faceCoordinatesBackup.put("right", rightC);
                    faceCoordinatesBackup.put("top", topC);
                    faceCoordinatesBackup.put("bottom", bottomC);
                    faceCoordinatesBackup.put("last", 0);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                //Log.e("coordinatesFrame", faceCoordinatesBackup.toString());
                return faceCoordinatesBackup.toString();
            } else {
                return "";
            }

        } else {
            return "";
        }
    }

    /*public String getFaceCoordinatesOnlyBackup(Bitmap bitmap) {
        JSONObject faceCoordinatesBackup = new JSONObject();
        if (faceCoordinatesBackupInt != null) {
            try {

                float ratio1 = (float) currentImageHeight/currentImageWidth;
                Log.e("vishwamSukshiRatio1", String.valueOf(ratio1));
                //float ratio2 = (float)

                float cardW = (float) currentImageWidth * 9 / 10;
                float cardH = cardW / 1.45f;

                float topFG = (faceCoordinatesBackupInt.getInt("top"));
                float bottomFG = (faceCoordinatesBackupInt.getInt("bottom"));
                float leftFG = (faceCoordinatesBackupInt.getInt("left"));
                float rightFG = (faceCoordinatesBackupInt.getInt("right"));

                float topI = (topFG * currentImageWidth) / currentScreenW;
                float bottomI = (bottomFG * currentImageWidth) / currentScreenW;
                float leftI = (leftFG * currentImageWidth) / currentScreenW;
                float rightI = (rightFG * currentImageWidth) / currentScreenW;

                float topC = topI - ((currentImageHeight - cardH)/2) - (cardH/10);
                float bottomC = bottomI - ((currentImageHeight - cardH)/2) - (cardH/10);
                float leftC = leftI - ((currentImageWidth - cardW)/2);
                float rightC = rightI - ((currentImageWidth - cardW)/2);

                faceCoordinatesBackup.put("left", leftC);
                faceCoordinatesBackup.put("right", rightC);
                faceCoordinatesBackup.put("top", topC);
                faceCoordinatesBackup.put("bottom", bottomC);
                faceCoordinatesBackup.put("last", 0);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //Log.e("coordinatesFrame", faceCoordinatesBackup.toString());
            return faceCoordinatesBackup.toString();
        } else {
            return "";
        }
    }*/
    /**
     * Method to instanstiate CamSourceClass.
     * **/
    private void createCameraSourceFront() {
        faceDect = new FaceDect(this, mGraphicOverlay);
        mCameraSource = new CameraSource.Builder(context, previewFaceDetector)
                .setFacing(CameraSource.CAMERA_FACING_BACK)
                .setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)
                .setRequestedFps(30.0f)
                .build();
        startCameraSource();
    }
    /**
     * Method to start camersource class.
     * **/
    private void startCameraSource() {
        if (mCameraSource != null) {
            try {
                mPreview.start(mCameraSource, mGraphicOverlay);
            } catch (IOException e) {
                mCameraSource.release();
                mCameraSource = null;
            }
        }
    }
    /**
     * Method to stop camSource class.
     * **/
    private void stopCameraSource() {
        mPreview.stop();
    }

    boolean okForStartCam = true;
    /**
     * Lifecycle method of activity invoked on activity goes into background to back online.
     * **/
    @Override
    protected void onResume() {
        super.onResume();

        if (okForStartCam) {

            if (wasActivityResumed) {
                createCameraSourceFront();
            }
            startCameraSource();
        }
    }

    /**
     * Interface Callback on shutter of camera invoked by cameraSource.
     * **/

    final CameraSource.ShutterCallback cameraSourceShutterCallback = new CameraSource.ShutterCallback() {
        @Override
        public void onShutter() {

            dialog.setMessage("Receiving Image...");
            dialog.setCancelable(false);
            dialog.show();
        }
    };
    /**
     * Interface callback on camerasocurcepicture taken.
     ***/
    final CameraSource.PictureCallback cameraSourcePictureCallback = new CameraSource.PictureCallback() {
        @SuppressLint("NewApi")
        @Override
        public void onPictureTaken(byte[] data) {
            stopCameraSource();
        }
    };
    /**
     * Method to invoked camersource take picture method of camera1.
     * **/
    public void takePicture() {
        if (mCameraSource != null)
            mCameraSource.takePicture(cameraSourceShutterCallback, cameraSourcePictureCallback);
    }
    /**
     * Lifecycle method invoked by the system onclose of activity.
     * **/
    @Override
    protected void onPause() {
        super.onPause();
        wasActivityResumed = true;
        stopCameraSource();
    }
    /**
     * Lifecycle method invoked by the system on Close of activiy just after on pause.
     * **/
    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopCameraSource();
        if (previewFaceDetector != null) {
            previewFaceDetector.release();
        }
    }
    /**
     * Lifecycle method invoked by the system on backbutton pressed.
     * **/
    @Override
    public void onBackPressed() {}
}