package com.epson.cameracopy.p006ui;

import android.content.Intent;
import android.hardware.Camera;
import android.hardware.SensorManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.p000v4.app.Fragment;
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 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 epson.print.imgsel.CameraCopyImageSelectActivity;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
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;

/* 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;
    /* access modifiers changed from: private */
    public 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();
    /* access modifiers changed from: private */
    public final AptSensorAdapter mSensorEventListener = new AptSensorAdapter();
    private TakePictureTask mTakePictureTask;
    private boolean noCameraDialog;

    private void startInformationActivity() {
    }

    static {
        OpenCVLoader.initDebug();
    }

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

    public boolean isPreviewActivityStarted() {
        return this.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);
        this.mOpenCvCameraView = (OpenCvCameraView) inflate.findViewById(R.id.view1);
        if (CameraPreviewControl.hasBackCamera()) {
            this.mHasCamera = true;
            this.mOpenCvCameraView.setCvCameraViewListener((CameraBridgeViewBase.CvCameraViewListener2) this);
        } else {
            this.mHasCamera = false;
            UiCommon.setButtonEnabled(this.mPhtographButton, false);
            if (bundle == null && this.noCameraDialog) {
                this.noCameraDialog = false;
                SimpleMessageDialogFragment.newInstance(R.string.back_camera_not_exists_message).show(getFragmentManager(), "error-dialog");
            }
        }
        this.mOpenCvCameraView.setVisibility(0);
        this.mDisplayRotation = ((WindowManager) getActivity().getSystemService("window")).getDefaultDisplay().getRotation();
        this.mSensorEventListener.setDisplayRotation(this.mDisplayRotation);
        this.mSensorEventListener.setSensorManager((SensorManager) getActivity().getSystemService("sensor"));
        this.mSensorEventListener.setReferenceAccelaration(REFERENCE_ACCELARATION);
        this.mFunctionBarView = inflate.findViewById(R.id.function_bar);
        this.mDisplayDensity = getActivity().getResources().getDisplayMetrics().density;
        return inflate;
    }

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

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

    /* access modifiers changed from: private */
    public void startPhotoSelectActivity() {
        startActivity(new Intent(getActivity(), CameraCopyImageSelectActivity.class));
    }

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

    private void savePictureSizeList() {
        List<Camera.Size> pictureSizeList;
        OpenCvCameraView openCvCameraView = this.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 = this.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;
            }
            this.mCameraPictureLowResolutionDialog = SimpleMessageDialogFragment.newInstance(i);
            this.mCameraPictureLowResolutionDialog.show(getFragmentManager(), "camera-resolution-warning-dialog");
        }
    }

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

    private void drawSensorPos(Mat mat, boolean z) {
        int i;
        int height = mat.height();
        if (height > 0) {
            double scale = (double) (1.0f / this.mOpenCvCameraView.getScale());
            int height2 = (int) (((double) this.mFunctionBarView.getHeight()) * scale);
            int height3 = (int) (((double) this.mOpenCvCameraView.getHeight()) * scale);
            double d = (double) height;
            if (height2 + 0 + height > height3) {
                i = (int) (((double) 0) - (((double) (height3 - height)) / 2.0d));
                d = (double) ((height3 - 0) - height2);
            } else {
                i = 0;
            }
            Size size = this.mRgba.size();
            double d2 = size.width / 2.0d;
            double d3 = d / 10.0d;
            double d4 = scale;
            double d5 = (double) 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(this.mRgba, point, point2, this.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(this.mRgba, point, point2, this.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(this.mRgba, point, point2, this.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(this.mRgba, point, point2, this.mGridColor, 2);
            point.f432x = d13;
            double d28 = d23;
            double d29 = d22;
            point.f433y = d29;
            point2.f432x = d15;
            point2.f433y = d29;
            Imgproc.line(this.mRgba, point, point2, this.mGridColor, 2);
            point.f432x = d25;
            point.f433y = d29;
            point2.f432x = d27;
            point2.f433y = d29;
            Imgproc.line(this.mRgba, point, point2, this.mGridColor, 2);
            point.f432x = d13;
            double d30 = d28;
            point.f433y = d30;
            point2.f432x = d13;
            double d31 = d26;
            point2.f433y = d31;
            Imgproc.line(this.mRgba, point, point2, this.mGridColor, 2);
            point.f432x = d13;
            double d32 = d24;
            point.f433y = d32;
            point2.f432x = d13;
            point2.f433y = d29;
            Imgproc.line(this.mRgba, point, point2, this.mGridColor, 2);
            point.f432x = d27;
            point.f433y = d30;
            point2.f432x = d27;
            point2.f433y = d31;
            Imgproc.line(this.mRgba, point, point2, this.mGridColor, 2);
            point.f432x = d27;
            point.f433y = d32;
            point2.f432x = d27;
            point2.f433y = d29;
            Imgproc.line(this.mRgba, point, point2, this.mGridColor, 2);
            if (z) {
                double posX = d12 - (((double) (this.mSensorEventListener.getPosX() * 0.05098581f)) * d12);
                double posY = d6 + (((double) (this.mSensorEventListener.getPosY() * 0.05098581f)) * d6) + d20;
                int i2 = (int) (d4 * 20.0d * ((double) this.mDisplayDensity));
                Imgproc.circle(this.mRgba, new Point(posX, posY), i2, this.mPositionCursorColor, 1);
                double d33 = (double) i2;
                Imgproc.line(this.mRgba, new Point(posX, posY - d33), new Point(posX, posY + d33), this.mPositionCursorColor);
                Imgproc.line(this.mRgba, new Point(posX - d33, posY), new Point(posX + d33, posY), this.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 this.mSensorEventListener.isTerminalAngleInRange(this.AUTO_PICTURE_RANGE_VALUE);
    }

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

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

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

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

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

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

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

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

    /* access modifiers changed from: private */
    public void showErrorDialog() {
        SimpleMessageDialogFragment.newInstance(R.string.file_save_error_message).show(getFragmentManager(), "error-dialog");
    }

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

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

    /* access modifiers changed from: private */
    public void enableAllButton() {
        if (CameraPreviewControl.hasBackCamera()) {
            UiCommon.setButtonEnabled(this.mPhtographButton, true);
            disableSettingButton(false);
        }
        UiCommon.setButtonEnabled(this.mPhotoSelectButton, true);
    }

    /* access modifiers changed from: private */
    public void disableAllButton() {
        UiCommon.setButtonEnabled(this.mPhtographButton, false);
        disableSettingButton(true);
        UiCommon.setButtonEnabled(this.mPhotoSelectButton, false);
    }

    /* access modifiers changed from: private */
    public void startPictureViewActivity(String str) {
        Intent intent = new Intent(getActivity(), ImagePreviewActivity.class);
        intent.putExtra(ImagePreviewActivity.PARAM_CAMERA_FILE, new CameraFile(new Date(), str));
        startActivity(intent);
        this.mPreviewActivityStarted = true;
    }

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

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

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

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

    public boolean onBackPressed() {
        return !this.mPictureTaking;
    }

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

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

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

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