package com.epson.cameracopy.ui;

import android.app.Service;
import android.content.Intent;
import android.hardware.Camera;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;

import androidx.fragment.app.Fragment;

import com.epson.cameracopy.alt.FileUtils;
import com.epson.cameracopy.alt.UiCommon;
import com.epson.cameracopy.device.AptSensorAdapter;
import com.epson.cameracopy.device.CameraFile;
import com.epson.cameracopy.device.CameraPreviewControl;
import com.epson.cameracopy.device.OpenCvCameraView;
import com.epson.cameracopy.device.RectangleDetector;

import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import epson.print.R;
import epson.print.imgsel.CameraCopyImageSelectActivity;

/* renamed from: com.epson.cameracopy.ui.CameraPreviewFragment */
public class CameraPreviewFragment extends Fragment implements CameraBridgeViewBase.CvCameraViewListener2, OpenCvCameraView.AutoFocusCallBack {
    private static final Scalar COLOR_BLACK = new Scalar(0.0d, 0.0d, 0.0d, 255.0d);
    private static final Scalar[] PAPER_SQUARE_COLOR = {new Scalar(255.0d, 0.0d, 0.0d, 255.0d), new Scalar(0.0d, 255.0d, 0.0d, 255.0d)};
    private static final Point POSITION_0_0 = new Point(0.0d, 0.0d);
    private static final double REFERENCE_ACCELARATION = 0.45d;
    private static final String TAG = "CameraPreviewFragment";
    private final double AUTO_PICTURE_RANGE_VALUE = AptSensorAdapter.getRangeCompValue(20);
    private final int INIT_SPAN = 2;
    private final double PAPER_DETECT_VALUE = AptSensorAdapter.getRangeCompValue(45);
    private boolean isFragmentVisible;
    private boolean mAutoPhotoMode;
    private final long mAutoPictureStillTime = 3000;
    private SimpleMessageDialogFragment mCameraPictureLowResolutionDialog;
    private CameraPreviewControl mCameraPreviewControl;
    private boolean mDisableSettingsButton = false;
    private float mDisplayDensity;
    private int mDisplayRotation;
    private View mFunctionBarView;
    private final Scalar mGridColor = new Scalar(255.0d, 163.0d, 0.0d, 255.0d);
    private final int mGridColorWidth = 1;
    private boolean mHasCamera;
    private int mInitCount;
    private OpenCvCameraView mOpenCvCameraView;
    private long mPAfTime;
    private final int mPaperSquareCircleSize = 20;
    private Button mPhotoSelectButton;
    private Button mPhtographButton;
    private volatile boolean mPictureTaking;
    private final Scalar mPositionCursorColor = new Scalar(255.0d, 0.0d, 0.0d, 255.0d);
    private final float mPositionCursorDispRate = 0.05098581f;
    private volatile boolean mPreviewActivityStarted;
    private Mat mRgba;
    private final Point mScreenSize = new Point();
    private final AptSensorAdapter mSensorEventListener = new AptSensorAdapter();
    private TakePictureTask mTakePictureTask;
    private boolean noCameraDialog;

    private void startInformationActivity() {
    }

    static {
        OpenCVLoader.initDebug();
    }

    public void setAppInitFlag(boolean z) {
        if (z) {
            noCameraDialog = true;
        }
    }

    public boolean isPreviewActivityStarted() {
        return mPreviewActivityStarted;
    }

    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        View inflate = layoutInflater.inflate(R.layout.fragment_camera_preview, viewGroup, false);
        setHasOptionsMenu(true);
        setButtonListener(inflate);
        mOpenCvCameraView = (OpenCvCameraView) inflate.findViewById(R.id.view1);
        if (CameraPreviewControl.hasBackCamera()) {
            mHasCamera = true;
            mOpenCvCameraView.setCvCameraViewListener((CameraBridgeViewBase.CvCameraViewListener2) this);
        } else {
            mHasCamera = false;
            UiCommon.setButtonEnabled(mPhtographButton, false);
            if (bundle == null && noCameraDialog) {
                noCameraDialog = false;
                SimpleMessageDialogFragment.newInstance(R.string.back_camera_not_exists_message).show(getFragmentManager(), "error-dialog");
            }
        }
        mOpenCvCameraView.setVisibility(View.VISIBLE);
        mDisplayRotation = ((WindowManager) getActivity().getSystemService(Service.WINDOW_SERVICE)).getDefaultDisplay().getRotation();
        mSensorEventListener.setDisplayRotation(mDisplayRotation);
        mSensorEventListener.setSensorManager((SensorManager) getActivity().getSystemService("sensor"));
        mSensorEventListener.setReferenceAccelaration(REFERENCE_ACCELARATION);
        mFunctionBarView = inflate.findViewById(R.id.function_bar);
        mDisplayDensity = getActivity().getResources().getDisplayMetrics().density;
        return inflate;
    }

    private void setButtonListener(View view) {
        mPhotoSelectButton = (Button) view.findViewById(R.id.photo_select_button);
        mPhotoSelectButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (!CameraPreviewFragment.mPictureTaking) {
                    CameraPreviewFragment.this.startPhotoSelectActivity();
                }
            }
        });
        mPhtographButton = (Button) view.findViewById(R.id.photograph_button);
        mPhtographButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                if (!CameraPreviewFragment.mPictureTaking) {
                    CameraPreviewFragment.this.takePicture();
                }
            }
        });
    }

    private void startSettingActivity() {
        startActivity(new Intent(getActivity(), CameraPreviewOptionActivity.class));
    }

    private void startPhotoSelectActivity() {
        startActivity(new Intent(getActivity(), CameraCopyImageSelectActivity.class));
    }

    public void onCameraViewStarted(int i, int i2) {
        mRgba = new Mat(i, i2, CvType.CV_8UC4);
        savePictureSizeList();
        checkPictureSize();
    }

    private void savePictureSizeList() {
        List<Camera.Size> pictureSizeList;
        OpenCvCameraView openCvCameraView = mOpenCvCameraView;
        if (openCvCameraView != null && (pictureSizeList = openCvCameraView.getPictureSizeList()) != null) {
            Iterator<Camera.Size> it = pictureSizeList.iterator();
            while (it.hasNext()) {
                Camera.Size next = it.next();
                if (next.width * next.height < 1000000) {
                    it.remove();
                }
            }
            CameraPreviewControl.getInstance(getActivity()).setCameraPictureSizes(pictureSizeList);
        }
    }

    private void checkPictureSize() {
        OpenCvCameraView openCvCameraView;
        Camera.Size cameraPictureSize;
        CameraPreviewControl instance = CameraPreviewControl.getInstance(getActivity());
        if (instance.getPictureResolutionMode() == 0 && (openCvCameraView = mOpenCvCameraView) != null && (cameraPictureSize = openCvCameraView.getCameraPictureSize()) != null && cameraPictureSize.width * cameraPictureSize.height < 1000000) {
            int i = R.string.camera_picture_low_message;
            List<android.graphics.Point> cameraPictureSizes = instance.getCameraPictureSizes();
            if (cameraPictureSizes == null || cameraPictureSizes.size() <= 0) {
                i = R.string.has_no_hireso_picture_message;
            }
            mCameraPictureLowResolutionDialog = SimpleMessageDialogFragment.newInstance(i);
            mCameraPictureLowResolutionDialog.show(getFragmentManager(), "camera-resolution-warning-dialog");
        }
    }

    public void onCameraViewStopped() {
        mRgba.release();
        SimpleMessageDialogFragment simpleMessageDialogFragment = mCameraPictureLowResolutionDialog;
        if (simpleMessageDialogFragment != null) {
            simpleMessageDialogFragment.dismiss();
            mCameraPictureLowResolutionDialog = null;
        }
    }

    private void drawSensorPos(Mat mat, boolean z) {
        int i;
        int height = mat.height();
        if (height > 0) {
            double scale = (1.0f / mOpenCvCameraView.getScale());
            int height2 = ((mFunctionBarView.getHeight()) * scale);
            int height3 = ((mOpenCvCameraView.getHeight()) * scale);
            double d = height;
            if (height2 + 0 + height > height3) {
                i = ((0) - (((height3 - height)) / 2.0d));
                d = ((height3 - 0) - height2);
            } else {
                i = 0;
            }
            Size size = mRgba.size();
            double d2 = size.width / 2.0d;
            double d3 = d / 10.0d;
            double d4 = scale;
            double d5 = i;
            Point point = new Point();
            double d6 = d / 2.0d;
            Point point2 = new Point();
            double d7 = size.width / 10.0d;
            double d8 = d2 - 1.0d;
            point.f432x = d8;
            point.f433y = d5 + d3;
            point2.f432x = d8;
            double d9 = d5 + d;
            point2.f433y = d9 - d3;
            Imgproc.line(mRgba, point, point2, mGridColor, 1);
            double d10 = d7;
            point.f432x = d10;
            double d11 = d5 + d6;
            point.f433y = d11;
            Size size2 = size;
            double d12 = d2;
            point2.f432x = size2.width - d10;
            point2.f433y = d11;
            Imgproc.line(mRgba, point, point2, mGridColor, 1);
            double d13 = size2.width / 20.0d;
            double d14 = d / 20.0d;
            double d15 = d13 * 3.0d;
            double d16 = d14 + d5;
            double d17 = 3.0d * d14;
            double d18 = size2.width - d13;
            double d19 = d5 + d17;
            double d20 = d5;
            double d21 = d9 - d17;
            double d22 = d9 - d14;
            point.f432x = d13;
            double d23 = d16;
            point.f433y = d23;
            point2.f432x = d15;
            point2.f433y = d23;
            double d24 = d21;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            double d25 = size2.width - d15;
            point.f432x = d25;
            point.f433y = d23;
            double d26 = d19;
            double d27 = d18;
            point2.f432x = d27;
            point2.f433y = d23;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            point.f432x = d13;
            double d28 = d23;
            double d29 = d22;
            point.f433y = d29;
            point2.f432x = d15;
            point2.f433y = d29;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            point.f432x = d25;
            point.f433y = d29;
            point2.f432x = d27;
            point2.f433y = d29;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            point.f432x = d13;
            double d30 = d28;
            point.f433y = d30;
            point2.f432x = d13;
            double d31 = d26;
            point2.f433y = d31;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            point.f432x = d13;
            double d32 = d24;
            point.f433y = d32;
            point2.f432x = d13;
            point2.f433y = d29;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            point.f432x = d27;
            point.f433y = d30;
            point2.f432x = d27;
            point2.f433y = d31;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            point.f432x = d27;
            point.f433y = d32;
            point2.f432x = d27;
            point2.f433y = d29;
            Imgproc.line(mRgba, point, point2, mGridColor, 2);
            if (z) {
                double posX = d12 - (((mSensorEventListener.getPosX() * 0.05098581f)) * d12);
                double posY = d6 + (((mSensorEventListener.getPosY() * 0.05098581f)) * d6) + d20;
                int i2 = (d4 * 20.0d * (mDisplayDensity));
                Imgproc.circle(mRgba, new Point(posX, posY), i2, mPositionCursorColor, 1);
                double d33 = i2;
                Imgproc.line(mRgba, new Point(posX, posY - d33), new Point(posX, posY + d33), mPositionCursorColor);
                Imgproc.line(mRgba, new Point(posX - d33, posY), new Point(posX + d33, posY), mPositionCursorColor);
            }
        }
    }

    private void myDrawRect(Mat mat, Point[] pointArr, boolean z) {
        if (pointArr != null && pointArr.length >= 1 && pointArr.length >= 2) {
            Scalar[] scalarArr = PAPER_SQUARE_COLOR;
            Scalar scalar = scalarArr[0];
            if (z) {
                scalar = scalarArr[1];
            }
            Imgproc.line(mat, pointArr[0], pointArr[1], scalar, 2);
            if (pointArr.length >= 3) {
                Imgproc.line(mat, pointArr[1], pointArr[2], scalar, 2);
                if (pointArr.length >= 4) {
                    Imgproc.line(mat, pointArr[0], pointArr[3], scalar, 2);
                    Imgproc.line(mat, pointArr[2], pointArr[3], scalar, 2);
                }
            }
        }
    }

    private boolean checkAutoPictureAngle() {
        return mSensorEventListener.isTerminalAngleInRange(AUTO_PICTURE_RANGE_VALUE);
    }

    private boolean checkAccelerrationTime() {
        long lastOverTime2 = mSensorEventListener.getLastOverTime2();
        if (lastOverTime2 > 0 && System.currentTimeMillis() - lastOverTime2 >= 3000) {
            return true;
        }
        return false;
    }

    private boolean autofousTime() {
        return System.currentTimeMillis() - mSensorEventListener.getLastOverTime2() >= 500;
    }

    private void sensorAndCamera() {
        if (isFragmentVisible) {
            long currentTimeMillis = System.currentTimeMillis();
            if (mAutoPhotoMode && mSensorEventListener.isTerminalAngleInRange(PAPER_DETECT_VALUE)) {
                boolean checkAutoPictureAngle = checkAutoPictureAngle();
                int detectAndDrawRectangle2 = RectangleDetector.detectAndDrawRectangle2(mRgba.getNativeObjAddr(), 0, mFunctionBarView.getHeight(), checkAutoPictureAngle);
                if (checkAutoPictureAngle && detectAndDrawRectangle2 == 1 && checkAccelerrationTime()) {
                    takePicture();
                    return;
                } else if (detectAndDrawRectangle2 != 0) {
                    mPAfTime = currentTimeMillis;
                }
            }
            if (!mPictureTaking && !mAutoPhotoMode && !mPictureTaking && currentTimeMillis - mPAfTime > 4000 && !mOpenCvCameraView.isInAutofocus() && autofousTime()) {
                mOpenCvCameraView.doAutofocus(this);
                mPAfTime = currentTimeMillis;
            }
        }
    }

    public Mat onCameraFrame(CameraBridgeViewBase.CvCameraViewFrame cvCameraViewFrame) {
        mRgba = cvCameraViewFrame.rgba();
        if (!mHasCamera || mPictureTaking) {
            return mRgba;
        }
        int i = mInitCount;
        if (i < 2) {
            mInitCount = i + 1;
            mScreenSize.f432x = mRgba.width();
            mScreenSize.f433y = mRgba.height();
            Imgproc.rectangle(mRgba, POSITION_0_0, mScreenSize, COLOR_BLACK, -1);
        }
        sensorAndCamera();
        if (mCameraPreviewControl.getGuideMode()) {
            drawSensorPos(mRgba, mSensorEventListener.isTerminalAngleInRange(PAPER_DETECT_VALUE));
        }
        return mRgba;
    }

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        mCameraPreviewControl = CameraPreviewControl.getInstance(getActivity());
        mPictureTaking = false;
    }

    public void onResume() {
        super.onResume();
        if (mHasCamera) {
            enableAllButton();
            if (mOpenCvCameraView.checkBackCamera()) {
                mOpenCvCameraView.enableView();
                mSensorEventListener.start();
                mPAfTime = 0;
            } else {
                UiCommon.setButtonEnabled(mPhtographButton, false);
                disableSettingButton(true);
                SimpleMessageDialogFragment.newInstance(R.string.back_camera_not_exists_message).show(getFragmentManager(), "error-dialog");
            }
            mPictureTaking = false;
        }
        mInitCount = 0;
        if (mPreviewActivityStarted) {
            mPreviewActivityStarted = false;
            mPictureTaking = false;
            enableAllButton();
        }
        mAutoPhotoMode = mCameraPreviewControl.getAutoPictureMode();
        isFragmentVisible = true;
    }

    public void onPause() {
        isFragmentVisible = false;
        mSensorEventListener.stop();
        TakePictureTask takePictureTask = mTakePictureTask;
        if (takePictureTask != null) {
            takePictureTask.cancel(false);
            mTakePictureTask = null;
        }
        OpenCvCameraView openCvCameraView = mOpenCvCameraView;
        if (openCvCameraView != null) {
            openCvCameraView.cancelAutofocus();
            mOpenCvCameraView.disableView();
        }
        mPictureTaking = false;
        super.onPause();
    }

    public void onDestroy() {
        OpenCvCameraView openCvCameraView = mOpenCvCameraView;
        if (openCvCameraView != null) {
            openCvCameraView.cancelAutofocus();
            mOpenCvCameraView.disableView();
            mOpenCvCameraView.setCvCameraViewListener((CameraBridgeViewBase.CvCameraViewListener2) null);
            mOpenCvCameraView = null;
        }
        super.onDestroy();
    }

    private void showErrorDialog() {
        SimpleMessageDialogFragment.newInstance(R.string.file_save_error_message).show(getFragmentManager(), "error-dialog");
    }

    public void takePicture() {
        if (!mPictureTaking) {
            mPictureTaking = true;
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    CameraPreviewFragment.this.disableAllButton();
                }
            });
            mSensorEventListener.stop();
            mTakePictureTask = new TakePictureTask(mOpenCvCameraView);
            mTakePictureTask.execute(new Void[0]);
        }
    }

    private void takePictureStep2() {
        mOpenCvCameraView.takePicture(FileUtils.getNewTemporaryJpegFile(getActivity()).getPath(), new OpenCvCameraView.MyPictureTakeCallback() {
            public void onMyPictureTaken(boolean z, String str) {
                if (!z || str == null) {
                    CameraPreviewFragment.this.enableAllButton();
                    CameraPreviewFragment.mSensorEventListener.start();
                    boolean unused = CameraPreviewFragment.mPictureTaking = false;
                    CameraPreviewFragment.this.showErrorDialog();
                    return;
                }
                CameraPreviewFragment.this.startPictureViewActivity(str);
            }
        });
    }

    private void enableAllButton() {
        if (CameraPreviewControl.hasBackCamera()) {
            UiCommon.setButtonEnabled(mPhtographButton, true);
            disableSettingButton(false);
        }
        UiCommon.setButtonEnabled(mPhotoSelectButton, true);
    }

    private void disableAllButton() {
        UiCommon.setButtonEnabled(mPhtographButton, false);
        disableSettingButton(true);
        UiCommon.setButtonEnabled(mPhotoSelectButton, false);
    }

    private void startPictureViewActivity(String str) {
        Intent intent = new Intent(getActivity(), ImagePreviewActivity.class);
        intent.putExtra(ImagePreviewActivity.PARAM_CAMERA_FILE, new CameraFile(new Date(), str));
        startActivity(intent);
        mPreviewActivityStarted = true;
    }

    public void onAutoFocusCompleted(boolean z) {
        mPAfTime = System.currentTimeMillis();
    }

    private void disableSettingButton(boolean z) {
        mDisableSettingsButton = z;
        getActivity().invalidateOptionsMenu();
    }

    public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
        if (!mDisableSettingsButton) {
            menuInflater.inflate(R.menu.camera_menu, menu);
        }
        super.onCreateOptionsMenu(menu, menuInflater);
    }

    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() != R.id.camera_setting) {
            return super.onOptionsItemSelected(menuItem);
        }
        if (mPictureTaking) {
            return false;
        }
        startSettingActivity();
        return true;
    }

    public boolean onBackPressed() {
        return !mPictureTaking;
    }

    /* renamed from: com.epson.cameracopy.ui.CameraPreviewFragment$TakePictureTask */
    class TakePictureTask extends AsyncTask<Void, Void, Void> {
        private OpenCvCameraView mMyOpenCvCameraView;

        public TakePictureTask(OpenCvCameraView openCvCameraView) {
            mMyOpenCvCameraView = openCvCameraView;
        }

        protected Void doInBackground(Void... voidArr) {
            System.currentTimeMillis();
            while (!isCancelled() && mMyOpenCvCameraView.isInAutofocus()) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        protected void onPostExecute(Void voidR) {
            CameraPreviewFragment.this.takePictureStep2();
        }
    }
}
