package ibase.android.visionselfie;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.graphics.drawable.Drawable;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CameraMetadata;
import android.hardware.camera2.CaptureRequest;
import android.hardware.camera2.CaptureResult;
import android.hardware.camera2.TotalCaptureResult;
import android.hardware.camera2.params.OutputConfiguration;
import android.hardware.camera2.params.StreamConfigurationMap;
import android.media.ExifInterface;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.Size;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ImageButton;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;


/**
 * A simple {@link Fragment} subclass.
 */
public class CameraFragment extends Fragment implements View.OnClickListener {


    private static final String TAG = "CameraFragment";
    private static final int REQUEST_CAMERA_PERMISSION = 1;
    private static final String FRAGMENT_DIALOG = "dialog";

    private static final SparseIntArray ORIENTATIONS = new SparseIntArray();

    static {
        ORIENTATIONS.append(Surface.ROTATION_0, 90);
        ORIENTATIONS.append(Surface.ROTATION_90, 0);
        ORIENTATIONS.append(Surface.ROTATION_180, 270);
        ORIENTATIONS.append(Surface.ROTATION_270, 180);
    }

    private int SCREEN_WIDTH = 0;
    private int SCREEN_HEIGHT = 0;


    /**
     * An {@link AutoFitTextureView} for camera preview.
     */
    private AutoFitTextureView mTextureView;

    /**
     * An additional thread for running tasks that shouldn't block the UI.
     */
    private HandlerThread mBackgroundThread;
    /**
     * A {@link Handler} for running tasks in the background.
     */
    private Handler mBackgroundHandler;
    /**
     * ID of the current {@link CameraDevice}.
     */
    private String mCameraId;

    private float ASPECT_RATIO_ERROR_RANGE = 0.1f;
    /**
     * Orientation of the camera sensor
     */
    private int mSensorOrientation;
    /**
     * Max preview width that is guaranteed by Camera2 API
     */
    private int MAX_PREVIEW_WIDTH = 1920;
//    private int MAX_PREVIEW_WIDTH = 1280;

    /**
     * Max preview height that is guaranteed by Camera2 API
     */
    private int MAX_PREVIEW_HEIGHT = 1080;
//    private int MAX_PREVIEW_HEIGHT = 720;
    /**
     * The {@link android.util.Size} of camera preview.
     */
    private Size mPreviewSize;

    /**
     * A {@link Semaphore} to prevent the app from exiting before closing the camera.
     */
    private Semaphore mCameraOpenCloseLock = new Semaphore(1);
    /**
     * A reference to the opened {@link CameraDevice}.
     */
    private CameraDevice mCameraDevice;
    /**
     * {@link CaptureRequest.Builder} for the camera preview
     */
    private CaptureRequest.Builder mPreviewRequestBuilder;
    /**
     * A {@link CameraCaptureSession } for camera preview.
     */
    private CameraCaptureSession mCaptureSession;
    /**
     * {@link CaptureRequest} generated by {@link #mPreviewRequestBuilder}
     */
    private CaptureRequest mPreviewRequest;
    /**
     * Camera state: Showing camera preview.
     */
    private static final int STATE_PREVIEW = 0;
    /**
     * Camera state: Waiting for the focus to be locked.
     */
    private static final int STATE_WAITING_LOCK = 1;

    /**
     * Camera state: Waiting for the exposure to be precapture state.
     */
    private static final int STATE_WAITING_PRECAPTURE = 2;

    /**
     * Camera state: Waiting for the exposure state to be something other than precapture.
     */
    private static final int STATE_WAITING_NON_PRECAPTURE = 3;

    /**
     * Camera state: Picture was taken.
     */
    private static final int STATE_PICTURE_TAKEN = 4;

    /**
     * The current state of camera state for taking pictures.
     *
     * @see #mCaptureCallback
     */
    private int mState = STATE_PREVIEW;
    /**
     * An {@link ImageReader} that handles still image capture.
     */
    private ImageReader mImageReader;

    private boolean mIsImageAvailable = false;

    private Image mCapturedImage;




    private IMainActivity mIMainActivity;
    private ImageView mStillShotImageViewClose;
    private ImageButton mBtnStillshot, mBtnInitSticker;
    private View viewOrientationBg, viewInitStickerBg, viewStillShotBg, viewBgSave,viewBgShare;
    private ImageButton mBtnSwitchOrientation, mBtnSave,mBtnShare;
    private Bitmap mCapturedBitmap;
    private BackgroundImageRotator mBackgroundImageRotater;

    public DrawableImageView mStillshotImageView;

    private View view_orientation_bg_close;
    private boolean mIsCurrentlyDrawing = false;

//    view_orientation_bg_save
//            ibtn_save

    public static String imageName;
    private boolean mImageIsSaved;
    private boolean wantToShare;
//    private String imageName;
    /*
    * view_orientation_bg_close
    iv_close_stillshot_view
    * */


    public static CameraFragment newInstance() {
        return new CameraFragment();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView: ");
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_camera, container, false);

    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onViewCreated: ");
        view.findViewById(R.id.stillshot).setOnClickListener(this);
        view.findViewById(R.id.switch_orientation).setOnClickListener(this);
        view.findViewById(R.id.ibtn_save).setOnClickListener(this);
        view.findViewById(R.id.init_sticker_icon).setOnClickListener(this);

        mStillshotImageView = view.findViewById(R.id.stillshot_imageview);
        mBtnStillshot = view.findViewById(R.id.stillshot);

        viewStillShotBg = view.findViewById(R.id.view_stillshot_bg);

        mBtnInitSticker = view.findViewById(R.id.init_sticker_icon);
        viewInitStickerBg = view.findViewById(R.id.view_orientation_bg_sticker_icon);

        viewOrientationBg = view.findViewById(R.id.view_orientation_bg);
        mBtnSwitchOrientation = view.findViewById(R.id.switch_orientation);


        mStillShotImageViewClose = view.findViewById(R.id.iv_close_stillshot_view);
        mStillShotImageViewClose.setOnClickListener(this);

        view_orientation_bg_close = view.findViewById(R.id.view_orientation_bg_close);

        mBtnSave = view.findViewById(R.id.ibtn_save);
        viewBgSave = view.findViewById(R.id.view_orientation_bg_save);

        mBtnShare = view.findViewById(R.id.ibtn_share);
        mBtnShare.setOnClickListener(this);
        viewBgShare = view.findViewById(R.id.view_orientation_bg_share);


        mTextureView = view.findViewById(R.id.texture);
        setMaxSizes();
        resetIconVisibilities();
    }

    private void resetIconVisibilities() {
        Log.d(TAG, "resetIconVisibilities: ");
        viewOrientationBg.setVisibility(View.VISIBLE);
        mBtnSwitchOrientation.setVisibility(View.VISIBLE);
//        mStillshotImageView.setVisibility(View.INVISIBLE);
        mBtnStillshot.setVisibility(View.VISIBLE);
        viewStillShotBg.setVisibility(View.VISIBLE);

        mBtnInitSticker.setVisibility(View.VISIBLE);
        viewInitStickerBg.setVisibility(View.VISIBLE);

        mStillShotImageViewClose.setVisibility(View.INVISIBLE);
        view_orientation_bg_close.setVisibility(View.INVISIBLE);

        mBtnSave.setVisibility(View.INVISIBLE);
        viewBgSave.setVisibility(View.INVISIBLE);

        mBtnShare.setVisibility(View.INVISIBLE);
        viewBgShare.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.stillshot:
                Log.d(TAG, "onClick: taking picture");
                takePicture();
                break;
            case R.id.switch_orientation:
                Log.d(TAG, "onClick: switching camera orientation");
                toggleCameraDisplayOrientation();
                break;
            case R.id.iv_close_stillshot_view:
                hideStillShotContainer();
                break;
            case R.id.ibtn_save:
                saveCapturedStillShotToDisk();

                break;
            case R.id.init_sticker_icon:
                toggleStickers();
                break;
            case R.id.ibtn_share:
                shareSavedImage();
                break;
        }

    }

    private void shareSavedImage() {

        wantToShare = true;
        if (mImageIsSaved) {
            Log.d(TAG, "shareSavedImage: ");
//            File myFile = Environment.getExternalStoragePublicDirectory("/VisionSelfie/" + imageName);
            File myFile = Environment.getExternalStoragePublicDirectory("/VisionMoments/" + imageName);
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
            String type = mime.getMimeTypeFromExtension(ext);
            Intent sharingIntent = new Intent("android.intent.action.SEND");
            sharingIntent.setType(type);
//        sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
            sharingIntent.putExtra("android.intent.extra.STREAM", FileProvider.getUriForFile(getActivity().getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", myFile));
            sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            startActivity(Intent.createChooser(sharingIntent, "Share using"));
        } else {
            saveCapturedStillShotToDisk();
        }



    }

    private void shareCapturedStillShotToSocialMedia(Bitmap bitmap, String fileName) {

//        private void shareBitmap(Bitmap bitmap) {

//            final String shareText = getString(R.string.share_text) + " "
//                    + getString(R.string.app_name) + " developed by "
//                    + "https://play.google.com/store/apps/details?id=" + getPackageName() + ": \n\n";

        try {
            File file = new File(getActivity().getExternalCacheDir(), "share.png");
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
            file.setReadable(true, false);
            final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_TEXT, fileName);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            intent.setType("image/png");
            startActivity(Intent.createChooser(intent, "Share image via"));

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

//        }
        /*try {
//            File file = new File(getContext().getCacheDir(), fileName + ".png");
            File file = new File(getContext().getCacheDir(), fileName );
            FileOutputStream fOut = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
            file.setReadable(true, false);
            final Intent intent = new Intent(android.content.Intent.ACTION_SEND);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
            intent.setType("image/png");
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }

        */
       /* Bitmap icon = mBitmap;
        Intent share = new Intent(Intent.ACTION_SEND);
        share.setType("image/jpeg");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
        try {
            f.createNewFile();
            FileOutputStream fo = new FileOutputStream(f);
            fo.write(bytes.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
        startActivity(Intent.createChooser(share, "Share Image"));*/
    }

    private void toggleStickers() {
        Log.d(TAG, "toggleStickers: Display Sticker called");
        mIMainActivity.toggleViewStickersFragment();
    }

    private void saveCapturedStillShotToDisk() {
        Log.d(TAG, "saveCapturedStillShotToDisk: saving image to disk.");
        if (mIsImageAvailable) {
            final ICallBack callBack = new ICallBack() {
                @Override
                public void done(Exception e) {
                    if (e == null) {
                        Log.d(TAG, "onImageSavedCallback: image saved!");
                        showSnackBar("Image saved", Snackbar.LENGTH_SHORT);

                        mImageIsSaved = true;

                        if (wantToShare) {
                            shareSavedImage();
                        }

//                        File imageFile = Environment.getExternalStoragePublicDirectory("/VisionSelfie/" + imageName);
                        File imageFile = Environment.getExternalStoragePublicDirectory("/VisionMoments/" + imageName);

                        MediaScannerConnection.scanFile(getActivity(), new String[]{imageFile.getPath()}, new String[]{"image/jpeg"}, null);
                        Log.d(TAG, "done: MediaScannerConnection");

                        /*--------------------*/
                        /*Log.d(TAG, "doInBackground: adjusting image for display...");
                        File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"/VisionSelfie/"+imageName);
//                        File file = new File(getActivity().getExternalFilesDir(null), "temp_image.jpg");
                        Log.d(TAG, "done: path: "+path);
                        final Uri tempImageUri = Uri.fromFile(path);

                        Bitmap bitmap = null;


                        try {
                            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), tempImageUri);
//                            shareCapturedStillShotToSocialMedia(bitmap,"Vision Selfie");
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        }*/
                        /*--------------------*/

                    } else {
                        Log.d(TAG, "done: error saving image " + e.getMessage());
                        showSnackBar("Error saving image", Snackbar.LENGTH_SHORT);
                    }

                }
            };

            if (mCapturedImage != null) {
                Log.d(TAG, "saveCapturedStillShotToDisk: Saving image to disk");
                mStillshotImageView.invalidate();

                Log.d(TAG, "saveCapturedStillShotToDisk: width: "+mStillshotImageView.getDrawable().getIntrinsicWidth());
                Log.d(TAG, "saveCapturedStillShotToDisk: height: "+mStillshotImageView.getDrawable().getIntrinsicHeight());
                Bitmap bitmap = Bitmap.createBitmap(mStillshotImageView.getDrawingCache());
                Log.d(TAG, "saveCapturedStillShotToDisk: bitmap: w*h "+ bitmap.getWidth() +" : "+ bitmap.getHeight());
                File path = Environment.getExternalStoragePublicDirectory("/VisionMoments");
//                File path = Environment.getExternalStoragePublicDirectory("/VisionSelfie");
//                File path = new File(Environment.getExternalStorageDirectory() + "/VisionSelfie");
//                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM+"/VisionSelfie");
//                File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES+"/VisionSelfie");
                if (!path.exists()) {
                    path.mkdirs();
                }
                File file = new File(String.valueOf(path));

                ImageSaver imageSaver = new ImageSaver(
                        bitmap,
//                        getActivity().getExternalFilesDir(null),
                        file,
                        callBack
                );
                mBackgroundHandler.post(imageSaver);


            }
        }

    }

    private void hideStillShotContainer() {
        mIMainActivity.showStatusBar();
        if (mIsImageAvailable) {
            mIsImageAvailable = false;
            mCapturedBitmap = null;
            mStillshotImageView.setImageBitmap(null);
            mStillshotImageView.reset();

            resetIconVisibilities();

            reopenCamera();
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            mIMainActivity = (IMainActivity) getActivity();
        } catch (ClassCastException e) {
            Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
        }
    }

    private void toggleCameraDisplayOrientation() {
        if (mCameraId.equals(mIMainActivity.getBackCameraId())) {
            mCameraId = mIMainActivity.getFrontCameraId();
            mIMainActivity.setCameraFrontFacing();
            closeCamera();
            reopenCamera();
            Log.d(TAG, "toggleCameraDisplayOrientation: switching to front-facing camera");
        } else if (mCameraId.equals(mIMainActivity.getFrontCameraId())) {
            mCameraId = mIMainActivity.getBackCameraId();
            mIMainActivity.setCameraBackFacing();
            closeCamera();
            reopenCamera();
            Log.d(TAG, "toggleCameraDisplayOrientation: switching to back-facing camera");
        } else {
            Log.d(TAG, "toggleCameraDisplayOrientation: error");
        }
    }

    /**
     * Initiate a still image capture.
     */
    private void takePicture() {
        lockFocus();
    }

    private void lockFocus() {
        Log.d(TAG, "lockFocus: ");

        try {
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_START);

            mState = STATE_WAITING_LOCK;
//            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler);
//
            captureStillPicture();
//        } catch (CameraAccessException e) {
//            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    private void setMaxSizes() {
        Point displaySize = new Point();
        getActivity().getWindowManager().getDefaultDisplay().getSize(displaySize);
        SCREEN_HEIGHT = displaySize.x;
        SCREEN_WIDTH = displaySize.y;

        Log.d(TAG, "setMaxSizes: screen width: " + SCREEN_WIDTH);
        Log.d(TAG, "setMaxSizes: screen height: " + SCREEN_HEIGHT);
    }

    @Override
    public void onResume() {
        Log.d(TAG, "onResume: ");
        super.onResume();

        startBackgroundThread();
        if (mIsImageAvailable) {
            mIMainActivity.hideStatusBar();
        } else {
//            mIMainActivity.showStatusBar();
            mIMainActivity.hideStatusBar();
            // When the screen is turned off and turned back on, the SurfaceTexture is already
            // available, and "onSurfaceTextureAvailable" will not be called. In that case, we can open
            // a camera and start preview from here (otherwise, we wait until the surface is ready in
            // the SurfaceTextureListener).
            reopenCamera();
        }
    }


    @Override
    public void onPause() {
        Log.d(TAG, "onPause: ");
        super.onPause();
        closeCamera();
        stopBackgroundThread();
        if (mBackgroundImageRotater != null) {
            mBackgroundImageRotater.cancel(true);
        }
    }


    /**
     * Starts a background thread and its {@link Handler}.
     */
    private void startBackgroundThread() {
        if (mBackgroundThread == null) {
            Log.d(TAG, "startBackgroundThread: called.");
            mBackgroundThread = new HandlerThread("CameraBackground");
            mBackgroundThread.start();
            mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
        }

    }

    /**
     * Stops the background thread and its {@link Handler}.
     */
    private void stopBackgroundThread() {
        if (mBackgroundThread != null) {
            mBackgroundThread.quitSafely();
            try {
                mBackgroundThread.join();
                mBackgroundThread = null;
                mBackgroundHandler = null;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void reopenCamera() {
        Log.d(TAG, "reopenCamera: ");
        if (mTextureView.isAvailable()) {
            Log.d(TAG, "reopenCamera: a surface is available");
            openCamera(mTextureView.getWidth(), mTextureView.getHeight());
        } else {
            Log.d(TAG, "reopenCamera: no surface is available");
            mTextureView.setSurfaceTextureListener(mSurfaceTextureListener);
        }

    }

    /**
     * Closes the current {@link CameraDevice}.
     */
    private void closeCamera() {
        Log.d(TAG, "closeCamera: ");
        try {
            mCameraOpenCloseLock.acquire();
            if (null != mCaptureSession) {
                mCaptureSession.close();
                mCaptureSession = null;
                Log.d(TAG, "closeCamera: mCaptureSession.close();");
            }
            if (null != mCameraDevice) {
                mCameraDevice.close();
                mCameraDevice = null;
                Log.d(TAG, "closeCamera: mCameraDevice.close();");
            }
            if (null != mImageReader) {
                mImageReader.close();
                mImageReader = null;
                Log.d(TAG, "closeCamera: mImageReader.close();");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera closing.", e);
        } finally {
            Log.d(TAG, "closeCamera: mCameraOpenCloseLock.release()");
            mCameraOpenCloseLock.release();
        }
    }


    private final TextureView.SurfaceTextureListener mSurfaceTextureListener = new TextureView.SurfaceTextureListener() {
        @Override
        public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
            Log.d(TAG, "onSurfaceTextureAvailable: w: " + width + " h: " + height);
            openCamera(width, height);
        }

        @Override
        public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
            Log.d(TAG, "onSurfaceTextureSizeChanged: w: " + width + " h: " + height);
            configureTransform(width, height);

        }

        @Override
        public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) {
            return true;
        }

        @Override
        public void onSurfaceTextureUpdated(SurfaceTexture surface) {

        }
    };

    /**
     * Configures the necessary {@link android.graphics.Matrix} transformation to `mTextureView`.
     * This method should be called after the camera preview size is determined in
     * setUpCameraOutputs and also the size of `mTextureView` is fixed.
     *
     * @param viewWidth  The width of `mTextureView`
     * @param viewHeight The height of `mTextureView`
     */
    private void configureTransform(int viewWidth, int viewHeight) {
        Activity activity = getActivity();
        if (null == mTextureView || null == mPreviewSize || null == activity) {
            return;
        }
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        Matrix matrix = new Matrix();
        RectF viewRect = new RectF(0, 0, viewWidth, viewHeight);
        Log.d(TAG, "configureTransform: viewWidth: " + viewWidth + ", viewHeight: " + viewHeight);
        Log.d(TAG, "configureTransform: previewWidth: " + mPreviewSize.getWidth() + ", previewHeight: " + mPreviewSize.getHeight());
        RectF bufferRect = new RectF(0, 0, mPreviewSize.getHeight(), mPreviewSize.getWidth());
        float centerX = viewRect.centerX();
        float centerY = viewRect.centerY();
        if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
            Log.d(TAG, "configureTransform: rotating from 90 or 270");
            bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY());
            matrix.setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL);
            float scale = Math.max(
                    (float) viewHeight / mPreviewSize.getHeight(),
                    (float) viewWidth / mPreviewSize.getWidth());
            matrix.postScale(scale, scale, centerX, centerY);
            matrix.postRotate(90 * (rotation - 2), centerX, centerY);
        } else if (Surface.ROTATION_180 == rotation) {
            Log.d(TAG, "configureTransform: rotating 180.");
            matrix.postRotate(180, centerX, centerY);
        }

        /*for strange device accounting start*/
        float screenAspectRatio = (float) SCREEN_WIDTH / (float) SCREEN_HEIGHT;
        float previewAspectRatio = (float) mPreviewSize.getWidth() / (float) mPreviewSize.getHeight();
        String roundedScreenAspectRatio = String.format("%.2f", screenAspectRatio);
        String roundedPreviewAspectRatio = String.format("%.2f", previewAspectRatio);
        if (!roundedPreviewAspectRatio.equals(roundedScreenAspectRatio)) {

            float scaleFactor = (screenAspectRatio / previewAspectRatio);
            Log.d(TAG, "configureTransform: scale factor: " + scaleFactor);

            float heightCorrection = (((float) SCREEN_HEIGHT * scaleFactor) - (float) SCREEN_HEIGHT) / 2;

            matrix.postScale(scaleFactor, 1);
            matrix.postTranslate(-heightCorrection, 0);

        }
        /*for strange device accounting start*/

        mTextureView.setTransform(matrix);
    }

    private void openCamera(int width, int height) {
        if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            requestCameraPermission();
            return;
        }

        /*original code working*/
        setupCameraOutputs(width, height);
        configureTransform(width, height);
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        try {
            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                throw new RuntimeException("Time out waiting to lock camera opening.");
            }
            manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
        }


        /*setupCameraOutputs(width, height);
        configureTransform(width, height);

        mTextureView.post(new Runnable() {
            @Override
            public void run() {

                mBackgroundHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        Activity activity = getActivity();
                        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
                        try {
                            if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
                                throw new RuntimeException("Time out waiting to lock camera opening.");
                            }
                            if (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                                // TODO: Consider calling
                                //    ActivityCompat#requestPermissions
                                // here to request the missing permissions, and then overriding
                                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                //                                          int[] grantResults)
                                // to handle the case where the user grants the permission. See the documentation
                                // for ActivityCompat#requestPermissions for more details.
                                return;
                            }
                            manager.openCamera(mCameraId, mStateCallback, mBackgroundHandler);
                        } catch (CameraAccessException e) {
                            e.printStackTrace();
                        } catch (InterruptedException e) {
                            throw new RuntimeException("Interrupted while trying to lock camera opening.", e);
                        }

                    }
                });


            }
        });*/


    }

    /**
     * {@link CameraDevice.StateCallback} is called when {@link CameraDevice} changes its state.
     */
    private CameraDevice.StateCallback mStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice camera) {
            // This method is called when the camera is opened.  We start camera preview here.
            mCameraOpenCloseLock.release();
            mCameraDevice = camera;
            createCameraPreviewSession();

        }

        @Override
        public void onDisconnected(@NonNull CameraDevice camera) {
            mCameraOpenCloseLock.release();
            camera.close();
            mCameraDevice = null;
        }

        @Override
        public void onError(@NonNull CameraDevice camera, int error) {
            Log.d(TAG, "onError: " + error);
            mCameraOpenCloseLock.release();
            camera.close();
            mCameraDevice = null;
            Activity activity = getActivity();
            if (null != activity) {
                activity.finish();
            }
        }
    };

    /**
     * Creates a new {@link CameraCaptureSession} for camera preview.
     */
    private void createCameraPreviewSession() {
        try {
            SurfaceTexture texture = mTextureView.getSurfaceTexture();
            assert texture != null;

            // We configure the size of default buffer to be the size of camera preview we want.
            texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());

            // This is the output Surface we need to start preview.
            Surface surface = new Surface(texture);

            // We set up a CaptureRequest.Builder with the output Surface.
            mPreviewRequestBuilder
                    = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
            mPreviewRequestBuilder.addTarget(surface);


            // Here, we create a CameraCaptureSession for camera preview.
            mCameraDevice.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                    new CameraCaptureSession.StateCallback() {

                        @Override
                        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
                            // The camera is already closed
                            if (null == mCameraDevice) {
                                return;
                            }

                            // When the session is ready, we start displaying the preview.
                            mCaptureSession = cameraCaptureSession;

                            try {
                                // Auto focus should be continuous for camera preview.
                                // Most new-ish phones can auto focus
                                mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                                        CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);


                                // Finally, we start displaying the camera preview.
                                mPreviewRequest = mPreviewRequestBuilder.build();
                                mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);
                            } catch (CameraAccessException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onConfigureFailed(
                                @NonNull CameraCaptureSession cameraCaptureSession) {
                            showSnackBar("Failed", Snackbar.LENGTH_LONG);
                        }
                    }, null
            );
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }


    private CameraCaptureSession.CaptureCallback mCaptureCallback = new CameraCaptureSession.CaptureCallback() {

        private void process(CaptureResult result) {
            switch (mState) {
                case STATE_PREVIEW: {
                    // We have nothing to do when the camera preview is working normally.
                    break;
                }
                case STATE_WAITING_LOCK: {
                    Integer afState = result.get(CaptureResult.CONTROL_AF_STATE);
                    if (afState == null) {
                        captureStillPicture();
                    } else if (CaptureResult.CONTROL_AF_STATE_FOCUSED_LOCKED == afState ||
                            CaptureResult.CONTROL_AF_STATE_NOT_FOCUSED_LOCKED == afState) {
                        // CONTROL_AE_STATE can be null on some devices
                        Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                        if (aeState == null ||
                                aeState == CaptureResult.CONTROL_AE_STATE_CONVERGED) {
                            mState = STATE_PICTURE_TAKEN;
                            captureStillPicture();
                        } else {
                            runPrecaptureSequence();
                        }
                    } else if (afState == CaptureResult.CONTROL_AF_STATE_INACTIVE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
                case STATE_WAITING_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null ||
                            aeState == CaptureResult.CONTROL_AE_STATE_PRECAPTURE ||
                            aeState == CaptureRequest.CONTROL_AE_STATE_FLASH_REQUIRED) {
                        mState = STATE_WAITING_NON_PRECAPTURE;
                    }
                    break;
                }
                case STATE_WAITING_NON_PRECAPTURE: {
                    // CONTROL_AE_STATE can be null on some devices
                    Integer aeState = result.get(CaptureResult.CONTROL_AE_STATE);
                    if (aeState == null || aeState != CaptureResult.CONTROL_AE_STATE_PRECAPTURE) {
                        mState = STATE_PICTURE_TAKEN;
                        captureStillPicture();
                    }
                    break;
                }
            }
        }

        @Override
        public void onCaptureProgressed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureResult partialResult) {
            super.onCaptureProgressed(session, request, partialResult);
            process(partialResult);
        }

        @Override
        public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
            super.onCaptureCompleted(session, request, result);
            process(result);
        }
    };

    /**
     * Run the precapture sequence for capturing a still image. This method should be called when
     * we get a response in {@link #mCaptureCallback} from {@link #lockFocus()}.
     */
    private void runPrecaptureSequence() {
        try {
        // This is how to tell the camera to trigger.
        mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER, CaptureRequest.CONTROL_AE_PRECAPTURE_TRIGGER_START);
        // Tell #mCaptureCallback to wait for the precapture sequence to be set.
        mState = STATE_WAITING_PRECAPTURE;

            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler);

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

    }

    /**
     * Capture a still picture. This method should be called when we get a response in
     * {@link #mCaptureCallback} from both {@link #lockFocus()}.
     */
    private void captureStillPicture() {
        Log.d(TAG, "captureStillPicture: capturing picture");
        try {
            final Activity activity = getActivity();
            if (null == activity || null == mCameraDevice) {
                return;
            }

            // This is the CaptureRequest.Builder that we use to take a picture.
            CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureBuilder.addTarget(mImageReader.getSurface());

            // Use the same AE and AF modes as the preview.
            captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                    CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

            // Orientation
            // Rotate the image from screen orientation to image orientation
            int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

            CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() {
                @Override
                public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {

                    unlockFocus();

                }
            };

            mCaptureSession.stopRepeating();
            mCaptureSession.abortCaptures();
            mCaptureSession.capture(captureBuilder.build(), captureCallback, null);


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

    }

    /**
     * Unlock the focus. This method should be called when still image capture sequence is
     * finished.
     */
    private void unlockFocus() {

        try {
            // Reset the auto-focus trigger
            mPreviewRequestBuilder.set(CaptureRequest.CONTROL_AF_TRIGGER, CameraMetadata.CONTROL_AF_TRIGGER_CANCEL);
            mCaptureSession.capture(mPreviewRequestBuilder.build(), mCaptureCallback, mBackgroundHandler);
            // After this, the camera will go back to the normal state of preview.
            mState = STATE_PREVIEW;
            mCaptureSession.setRepeatingRequest(mPreviewRequest, mCaptureCallback, mBackgroundHandler);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
    }

    /**
     * This a callback object for the {@link ImageReader}. "onImageAvailable" will be called when a
     * still image is ready to be saved.
     */
    private final ImageReader.OnImageAvailableListener mOnImageAvailableListener = new ImageReader.OnImageAvailableListener() {

        @Override
        public void onImageAvailable(ImageReader reader) {
            Log.d(TAG, "onImageAvailable: called.");

            if (!mIsImageAvailable) {
                mCapturedImage = reader.acquireLatestImage();

                Log.d(TAG, "onImageAvailable: captured image width : " + mCapturedImage.getWidth());
                Log.d(TAG, "onImageAvailable: captured image height : " + mCapturedImage.getHeight());


                saveTempImageToStorage();

                /*final Activity activity = getActivity();
                if (activity != null) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Glide.with(activity)
                                    .load(mCapturedImage)
                                    .into(mStillshotImageView);

                            showStillShotContainer();
                        }
                    });
                }*/
            }


        }
    };

    private void saveTempImageToStorage() {

        Log.d(TAG, "saveTempImageToStorage: saving temp image to disk.");

        final ICallBack callBack = new ICallBack() {
            @Override
            public void done(Exception e) {
                if (e == null) {
                    Log.d(TAG, "done: onImageSavedCallback: image saved!");

                    mBackgroundImageRotater = new BackgroundImageRotator(getActivity());
                    mBackgroundImageRotater.execute();

                    mIsImageAvailable = true;
                    mCapturedImage.close();

                } else {
                    Log.d(TAG, "done: onImageSavedCallback: error saving image: " + e.getMessage());
                    showSnackBar("Error displaying image", Snackbar.LENGTH_SHORT);
                }
            }
        };

        if (getActivity() != null) {

            ImageSaver imageSaver = new ImageSaver(getActivity().getExternalFilesDir(null), mCapturedImage, callBack);
//            ImageSaver imageSaver = new ImageSaver(Environment.getExternalStorageDirectory(), mCapturedImage, callBack);
            mBackgroundHandler.post(imageSaver);
        }


    }

    public void addSticker(Drawable sticker) {
//        Log.d(TAG, "addSticker: sticker "+sticker.toString()+" sticker"+ sticker.getIntrinsicHeight() + " width "+sticker.getIntrinsicWidth());
        mStillshotImageView.reset();
        mStillshotImageView.addNewSticker(sticker);
    }

    public void drawingStarted() {
        if(!mIsCurrentlyDrawing){


            mIsCurrentlyDrawing = true;
        }
    }

    public void drawingStopped() {
        if(mIsCurrentlyDrawing){

            mIsCurrentlyDrawing = false;
        }
    }

    /**
     * Saves a JPEG {@link Image} into the specified {@link File}.
     */
    private static class ImageSaver implements Runnable {
        /**
         * The file we save the image into.
         */
        private final File mFile;

        /**
         * Original image that was captured
         */
        private Image mImage;

        private ICallBack mCallback;

        private Bitmap bitmap;


        public ImageSaver(File mFile, Image mImage, ICallBack mCallback) {
            this.mFile = mFile;
            this.mImage = mImage;
            this.mCallback = mCallback;
        }

        public ImageSaver(Bitmap bitmap, File mFile, ICallBack mCallback) {
            this.bitmap = bitmap;
            this.mFile = mFile;
            this.mCallback = mCallback;

        }

        @Override
        public void run() {

            if (mImage != null) {
                ByteBuffer buffer = mImage.getPlanes()[0].getBuffer();
                byte[] bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                FileOutputStream output = null;
                try {
                    File file = new File(mFile, "temp_image.jpg");
//                    File file = new File(mFile, "VS_"+getCurrentDateTime()+".jpg");
                    output = new FileOutputStream(file);
                    output.write(bytes);

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                    mCallback.done(e);
                } catch (IOException e) {
                    e.printStackTrace();
                    mCallback.done(e);
                } finally {
                    mImage.close();
                    if (null != output) {
                        try {
                            output.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                    mCallback.done(null);
                }


            } else if (bitmap != null) {
                ByteArrayOutputStream stream = null;
                byte[] imageByteArray = null;
                stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
                imageByteArray = stream.toByteArray();

                SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
                String format = s.format(new Date());
                File file = new File(mFile, "image_" + format + ".jpg");
                Log.d(TAG, "run: file: "+file.getAbsolutePath());
                imageName = file.getAbsolutePath();
                imageName = imageName.substring(file.getAbsolutePath().lastIndexOf("/")+1);
                //file: /storage/emulated/0/Pictures/VisionSelfie/image_28062019065752.jpg
//                imageName = String.valueOf(file.getAbsolutePath().lastIndexOf("/"));
//                imageName = file.getAbsolutePath().lastIndexOf("/");
                Log.d(TAG, "run:imageName "+ imageName);

                // save the mirrored byte array
                FileOutputStream output = null;
                try {
                    output = new FileOutputStream(file);
                    output.write(imageByteArray);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    mCallback.done(e);
                    e.printStackTrace();
                }finally {
                    if (null != output) {
                        try {
                            output.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mCallback.done(null);
                    }
                }
            }

        }

        private String getCurrentDateTime() {

            long date = System.currentTimeMillis();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH);


            return simpleDateFormat.format(date);
        }
    }


    /**
     * WARNING!
     * Can cause memory leaks! To prevent this the object is a global and CANCEL is being called
     * in "OnPause".
     */

    private class BackgroundImageRotator extends AsyncTask<Void, Integer, Integer> {

        Activity mActivity;

        public BackgroundImageRotator(Activity mActivity) {
            this.mActivity = mActivity;
        }

        @Override
        protected Integer doInBackground(Void... voids) {
            Log.d(TAG, "doInBackground: adjusting image for display...");
            File file = new File(mActivity.getExternalFilesDir(null), "temp_image.jpg");
            final Uri tempImageUri = Uri.fromFile(file);

            Bitmap bitmap = null;

            try {
                ExifInterface exifInterface = new ExifInterface(tempImageUri.getPath());
                bitmap = MediaStore.Images.Media.getBitmap(mActivity.getContentResolver(), tempImageUri);
                int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
                mCapturedBitmap = rotateBitmap(bitmap, orientation);
            } catch (IOException e) {
                e.printStackTrace();
                return 0;
            }

            return 1;
        }

        @Override
        protected void onPostExecute(Integer integer) {
            super.onPostExecute(integer);
            if (integer == 1) {
                displayCapturedImage();
            } else {
                showSnackBar("Error preparing image", Snackbar.LENGTH_SHORT);
            }
        }
    }

    private void displayCapturedImage() {
        Log.d(TAG, "displayCapturedImage: displaying stillshot image");

        final Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    RequestOptions requestOptions = new RequestOptions()
                            .diskCacheStrategy(DiskCacheStrategy.NONE)
                            .skipMemoryCache(true)
                            .dontTransform()
                            .centerCrop();

//                    Glide.with(activity)
                    GlideApp.with(activity)
                            .setDefaultRequestOptions(requestOptions)
                            .load(mCapturedBitmap)
//                            .load(mStillshotImageView.scaleToActualAspectRatio(mCapturedBitmap))
                            .into(mStillshotImageView);

                    showStillShotContainer();
                }
            });
        }

    }

    private void showStillShotContainer() {
        mBtnSwitchOrientation.setVisibility(View.INVISIBLE);
        mBtnStillshot.setVisibility(View.INVISIBLE);
        viewStillShotBg.setVisibility(View.INVISIBLE);
        viewOrientationBg.setVisibility(View.INVISIBLE);

        mBtnInitSticker.setVisibility(View.INVISIBLE);
        viewInitStickerBg.setVisibility(View.INVISIBLE);

        mStillShotImageViewClose.setVisibility(View.VISIBLE);
        view_orientation_bg_close.setVisibility(View.VISIBLE);

        mBtnSave.setVisibility(View.VISIBLE);
        viewBgSave.setVisibility(View.VISIBLE);

        mBtnShare.setVisibility(View.VISIBLE);
        viewBgShare.setVisibility(View.VISIBLE);

        mIMainActivity.hideStatusBar();
        closeCamera();

    }

    private Bitmap rotateBitmap(Bitmap bitmap, int orientation) {
        Matrix matrix = new Matrix();
        switch (orientation) {
            case ExifInterface.ORIENTATION_TRANSPOSE:
                Log.d(TAG, "rotateBitmap: transpose");
                matrix.setRotate(90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_NORMAL:
                Log.d(TAG, "rotateBitmap: normal.");
                return bitmap;
            case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
                Log.d(TAG, "rotateBitmap: flip horizontal");
                matrix.setScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_180:
                Log.d(TAG, "rotateBitmap: rotate 180");
                matrix.setRotate(180);
                break;
            case ExifInterface.ORIENTATION_FLIP_VERTICAL:
                Log.d(TAG, "rotateBitmap: rotate vertical");
                matrix.setRotate(180);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_90:
                Log.d(TAG, "rotateBitmap: rotate 90");
                matrix.setRotate(90);
                break;
            case ExifInterface.ORIENTATION_TRANSVERSE:
                Log.d(TAG, "rotateBitmap: transverse");
                matrix.setRotate(-90);
                matrix.postScale(-1, 1);
                break;
            case ExifInterface.ORIENTATION_ROTATE_270:
                Log.d(TAG, "rotateBitmap: rotate 270");
                matrix.setRotate(-90);
                break;
        }
        try {
            if (mIMainActivity.isCameraFrontFacing()) {
                Log.d(TAG, "rotateBitmap: MIRRORING IMAGE.");
                matrix.postScale(-1.0f, 1.0f);
            }

            Bitmap bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
//            bitmap.recycle();

            return bmRotated;
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * Retrieves the JPEG orientation from the specified screen rotation.
     *
     * @param rotation The screen rotation.
     * @return The JPEG orientation (one of 0, 90, 270, and 360)
     */
    private int getOrientation(int rotation) {
        // Sensor orientation is 90 for most devices, or 270 for some devices (eg. Nexus 5X)
        // We have to take that into account and rotate JPEG properly.
        // For devices with orientation of 90, we simply return our mapping from ORIENTATIONS.
        // For devices with orientation of 270, we need to rotate the JPEG 180 degrees.
        return (ORIENTATIONS.get(rotation) + mSensorOrientation + 270) % 360;
    }


    /**
     * Sets up member variables related to camera.
     *
     * @param width  The width of available size for camera preview
     * @param height The height of available size for camera preview
     */
    private void setupCameraOutputs(int width, int height) {
        Activity activity = getActivity();
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);


        try {
            Log.d(TAG, "setupCameraOutputs: called");
            if (!mIMainActivity.isCameraFrontFacing() && !mIMainActivity.isCameraBackFacing()) {
                Log.d(TAG, "setupCameraOutputs: finding camera id's");
                findCameraIds();
            }
            CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraId);
            Log.d(TAG, "setupCameraOutputs: camera id: " + mCameraId);

            StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
            assert map != null;

            Size largest = null;
            float screenAspectRatio = (float) SCREEN_WIDTH / (float) SCREEN_HEIGHT;
            List<Size> sizes = new ArrayList<>();
            for (Size size : Arrays.asList(map.getOutputSizes(ImageFormat.JPEG))) {
                float temp = (float) size.getWidth() / (float) size.getHeight();

                Log.d(TAG, "setupCameraOutputs: temp: " + temp);
                Log.d(TAG, "setupCameraOutputs: w: " + size.getWidth() + " h: " + size.getHeight());

                if (temp > (screenAspectRatio - screenAspectRatio * ASPECT_RATIO_ERROR_RANGE) && temp < (screenAspectRatio + screenAspectRatio * ASPECT_RATIO_ERROR_RANGE)) {
                    sizes.add(size);
                    Log.d(TAG, "setUpCameraOutputs: found a valid size: w: " + size.getWidth() + ", h: " + size.getHeight());
                }
            }
            if (sizes.size() > 0) {
                largest = Collections.max(sizes, new Utility.CompareSizesByArea());
                Log.d(TAG, "setUpCameraOutputs: largest width: " + largest.getWidth());
                Log.d(TAG, "setUpCameraOutputs: largest height: " + largest.getHeight());
            }

            // Find out if we need to swap dimension to get the preview size relative to sensor
            // coordinate.
            int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
            //noinspection ConstantConditions
            mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
            boolean swappedDimensions = false;
            switch (displayRotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_180:
                    if (mSensorOrientation == 90 || mSensorOrientation == 270) {
                        swappedDimensions = true;
                    }
                    break;
                case Surface.ROTATION_90:
                case Surface.ROTATION_270:
                    if (mSensorOrientation == 0 || mSensorOrientation == 180) {
                        swappedDimensions = true;
                    }
                    break;
                default:
                    Log.e(TAG, "Display rotation is invalid: " + displayRotation);
            }

            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            int rotatedPreviewWidth = width;
            int rotatedPreviewHeight = height;
            int maxPreviewWidth = displaySize.x;
            int maxPreviewHeight = displaySize.y;

            if (swappedDimensions) {
                rotatedPreviewWidth = height;
                rotatedPreviewHeight = width;
                maxPreviewWidth = displaySize.y;
                maxPreviewHeight = displaySize.x;
            }

            if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                maxPreviewWidth = MAX_PREVIEW_WIDTH;
            }

            if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                maxPreviewHeight = MAX_PREVIEW_HEIGHT;
            }

            Log.d(TAG, "setUpCameraOutputs: max preview width: " + maxPreviewWidth);
            Log.d(TAG, "setUpCameraOutputs: max preview height: " + maxPreviewHeight);

            /*if (largest != null) {

                mPreviewSize = Utility.chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                        rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                        maxPreviewHeight, largest);
            }*/

            mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, 2);
            mImageReader.setOnImageAvailableListener(mOnImageAvailableListener, mBackgroundHandler);


            mPreviewSize = Utility.chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                    rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                    maxPreviewHeight, largest);

            /*mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),
                    rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth,
                    maxPreviewHeight, largest);*/

            Log.d(TAG, "setUpCameraOutputs: preview width: " + mPreviewSize.getWidth());
            Log.d(TAG, "setUpCameraOutputs: preview height: " + mPreviewSize.getHeight());

            // We fit the aspect ratio of TextureView to the size of preview we picked.
            int orientation = getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                mTextureView.setAspectRatio(
//                        mPreviewSize.getWidth(), mPreviewSize.getHeight(), SCREEN_WIDTH, SCREEN_HEIGHT);
                        mPreviewSize.getWidth(), mPreviewSize.getHeight());
            } else {
                mTextureView.setAspectRatio(
//                        mPreviewSize.getHeight(), mPreviewSize.getWidth(), SCREEN_HEIGHT, SCREEN_WIDTH);
                        mPreviewSize.getHeight(), mPreviewSize.getWidth());
            }

            Log.d(TAG, "setUpCameraOutputs: cameraId: " + mCameraId);

        } catch (CameraAccessException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            // Currently an NPE is thrown when the Camera2API is used but not supported on the
            // device this code runs.
            ErrorDialog.newInstance(getString(R.string.camera_error))
                    .show(getChildFragmentManager(), FRAGMENT_DIALOG);
        }


    }

    private void findCameraIds() {
        Activity activity = getActivity();
        if (activity != null) {

            CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);

            try {
                for (String cameraId : manager.getCameraIdList()) {
                    Log.d(TAG, "setCameraOrientation: CAMERA ID: " + cameraId);
                    if (cameraId == null) continue;
                    CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                    int facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                    if (facing == CameraCharacteristics.LENS_FACING_FRONT) {
//                    mCameraId = cameraId;
                        mIMainActivity.setFrontCameraId(cameraId);
                    } else if (facing == CameraCharacteristics.LENS_FACING_BACK) {
//                    mCameraId = cameraId;
                        mIMainActivity.setBackCameraId(cameraId);
                    }
                }
//                mIMainActivity.setCameraBackFacing();
                mIMainActivity.setCameraFrontFacing();
                mCameraId = mIMainActivity.getFrontCameraId();
//                mCameraId = mIMainActivity.getBackCameraId();
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
    }

    private void requestCameraPermission() {
        if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) {
            new ConfirmationDialog().show(getChildFragmentManager(), FRAGMENT_DIALOG);
        } else {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
        }
    }


    /**
     * Shows an error message dialog.
     */
    public static class ErrorDialog extends DialogFragment {

        private static final String ARG_MESSAGE = "message";

        public static ErrorDialog newInstance(String message) {
            ErrorDialog dialog = new ErrorDialog();
            Bundle args = new Bundle();
            args.putString(ARG_MESSAGE, message);
            dialog.setArguments(args);
            return dialog;
        }

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Activity activity = getActivity();
            return new AlertDialog.Builder(activity)
                    .setMessage(getArguments().getString(ARG_MESSAGE))
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            activity.finish();
                        }
                    })
                    .create();
        }

    }

    /**
     * Shows OK/Cancel confirmation dialog about camera permission.
     */
    public static class ConfirmationDialog extends DialogFragment {

        @NonNull
        @Override
        public Dialog onCreateDialog(Bundle savedInstanceState) {
            final Fragment parent = getParentFragment();
            return new AlertDialog.Builder(getActivity())
                    .setMessage(R.string.request_permission)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            parent.requestPermissions(new String[]{Manifest.permission.CAMERA},
                                    REQUEST_CAMERA_PERMISSION);
                        }
                    })
                    .setNegativeButton(android.R.string.cancel,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Activity activity = parent.getActivity();
                                    if (activity != null) {
                                        activity.finish();
                                    }
                                }
                            })
                    .create();
        }
    }

    /**
     * Shows a {@link Snackbar} on the UI thread.
     *
     * @param text The message to show
     */
    private void showSnackBar(final String text, final int length) {
        final Activity activity = getActivity();
        if (activity != null) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    View view = activity.findViewById(android.R.id.content).getRootView();
                    Snackbar.make(view, text, length).show();
                }
            });
        }





    }

    /*/////////////////////////////////////////////////////////////*/

    //Samsung-S6-choices[0]
//Samsung-S7-edge-choices[6]
//OnePlus-5T-choices[15]
    /*
     * Given {@code choices} of {@code Size}s supported by a camera, chooses the smallest one whose
     * width and height are at least as large as the respective requested values, and whose aspect
     * ratio matches with the specified value.
     *
     * @param choices     The list of sizes that the camera supports for the intended output class
     * @param width       The minimum desired width
     * @param height      The minimum desired height
     * @param aspectRatio The aspect ratio
     * @return The optimal {@code Size}, or an arbitrary one if none were big enough
     */
    private  Size chooseOptimalSize(Size[] choices, int screenWidth, int screenHeight, int width, int height, Size aspectRatio) {
        // Collect the supported resolutions that are at least as big as the preview Surface
        List<Size> bigEnough = new ArrayList<>();
        int w = aspectRatio.getWidth();
        int h = aspectRatio.getHeight();
        double ratio = (double) h / w;
        int loopCounter=0;
        for (Size size : choices) {
            int orientation = getActivity().getResources().getConfiguration().orientation;
            if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
                //if((size.getWidth()/16) == (size.getHeight()/9) && size.getWidth() <=720) {
                //if((size.getWidth()/16) == (size.getHeight()/9) && size.getWidth() <=3840 ) {
                //if((size.getWidth()/16) == (size.getHeight()/9) && size.getWidth() <=5120 ) {//Retina 5K
                if((size.getWidth()/16) == (size.getHeight()/9) && size.getWidth() <=7680 ) {//8K UHDTV Super Hi-Vision
                    Log.e(TAG, "chooseOptimalSize:"+size);
                    return size;
                }
            } else {
                Log.e(TAG, "chooseOptimalSize:--given--"+size);
                DisplayMetrics metrics = getActivity().getResources().getDisplayMetrics();
                float mCameraAspectRatio = ((float)metrics.heightPixels / (float)metrics.widthPixels);
                Log.e(TAG, "chooseOptimalSize:--AspectRatio--"+mCameraAspectRatio);
                if((size.getWidth()/16) == (size.getHeight()/9) && ((size.getWidth() <=1280)||(size.getHeight()<=1920))) {
                    //if((size.getWidth()/16) == (size.getHeight()/9) && (size.getWidth() <=4320 ) ) {//8K UHDTV Super Hi-Vision
                    //if((size.getWidth()/16) == (size.getHeight()/9) && (size.getWidth() <=2880 ) ) {//Retina 5K
                    //if((size.getWidth()/16) == (size.getHeight()/9) && (size.getWidth() <=2160 ) ) {
                    //if((size.getWidth()/16) == (size.getHeight()/9) && (size.getWidth() <=1280 ) ) {
                    //if((size.getWidth()/16) == (size.getHeight()/9) && (size.getWidth() <=4480 && size.getWidth() >=1280) ) {
                    Log.e(TAG, "chooseOptimalSize:"+size+"-16:9");
                    return size;
                }else if((size.getWidth()/18) == (size.getHeight()/9) && ((size.getWidth() <=3840)||(size.getHeight()<=2160))) {
                    Log.e(TAG, "chooseOptimalSize:"+size+"-18:9");
                    return size;
                }else if((size.getWidth()/18.5) == (size.getHeight()/9) && ((size.getWidth() <=3840)||(size.getHeight()<=2160))) {
                    Log.e(TAG, "chooseOptimalSize:"+size+"-18.5:9");
                    return size;
                }else if((size.getWidth()/19) == (size.getHeight()/9) && ((size.getWidth() <=3840)||(size.getHeight()<=2160))) {
                    Log.e(TAG, "chooseOptimalSize:"+size+"-19:9");
                    return size;
                }else if((size.getWidth()/19.5) == (size.getHeight()/9) && ((size.getWidth() <=3840)||(size.getHeight()<=2160))) {
                    Log.e(TAG, "chooseOptimalSize:"+size+"-19.5:9");
                    return size;
                }else{
                    Log.e(TAG, "chooseOptimalSize"+" not proper aspect resolution");
                    Log.e(TAG, "chooseOptimalSize"+" ---=>Width---=>"+size.getWidth());
                    Log.e(TAG, "chooseOptimalSize"+" ---=>Height---=>"+size.getHeight());
                }
                //2340
            }

            if(screenWidth==size.getWidth()){
                Log.e(TAG, loopCounter+".choose:width Matched:"+screenWidth+"="+size.getWidth());
            }else{
                Log.e(TAG, loopCounter+".choose:width Not Matched:"+screenWidth+"="+size.getWidth());
            }

            if(screenHeight==size.getHeight()){
                Log.e(TAG, loopCounter+".choose:height Matched:"+screenHeight+"="+size.getHeight());
            }else{
                Log.e(TAG, loopCounter+".choose:height Not Matched:"+screenHeight+"="+size.getHeight());
            }
            loopCounter++;
        }
        // Pick the smallest of those, assuming we found any
        if (bigEnough.size() > 0) {
            return Collections.min(bigEnough, new CompareSizesByArea());
        } else {
            Log.e(TAG, "Couldn't find any suitable preview size");
            return choices[0];
        }
    }


    /*
     * Compares two {@code Size}s based on their areas.
     */
    static class CompareSizesByArea implements Comparator<Size> {
        @Override
        public int compare(Size lhs, Size rhs) {
            // We cast here to ensure the multiplications won't overflow
            return Long.signum((long) lhs.getWidth() * lhs.getHeight() -
                    (long) rhs.getWidth() * rhs.getHeight());
        }
    }
}
