package org.lasarobotics.vision.test.opmode.extensions;

import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;

import org.lasarobotics.vision.test.opmode.VisionOpMode;
import org.opencv.core.Mat;

import org.lasarobotics.vision.test.detection.QRDetector;

/**
 * Uses ZXing library to detect QR codes
 */
public class QRExtension implements VisionExtension {
    private QRDetector qrd;
    private Result lastResult;

    private String text;
    public boolean hasText()
    {
        return text != null;
    }
    public String getText()
    {
        return text != null ? text : "";
    }

    @Override
    public void init(VisionOpMode opmode) {
        qrd = new QRDetector();
    }

    public QRDetector.Orientation getOrientation() {
        return QRDetector.getOrientation(lastResult.getResultPoints());
    }

    @Override
    public void loop(VisionOpMode opmode) {
        //do nothing
    }

    @Override
    public Mat frame(VisionOpMode opmode, Mat rgba, Mat gray) {
        try {
            lastResult = qrd.detectFromMat(rgba);
            text = lastResult.getText();
        } catch(NotFoundException|ChecksumException|FormatException ex) {
            text = null;
        }
        return rgba;
    }

    @Override
    public void stop(VisionOpMode opmode) {
        //do nothing
    }
}
@@ -518,16 +518,179 @@
 esult;%0A%0A
+    private String reason;%0A    public boolean hasErrorReason() %7B return reason != null; %7D%0A    public String getErrorReason() %7B return text != null ? text : %22%22; %7D%0A%0A
     priv
@@ -1368,97 +1368,489 @@
     
-%7D catch(NotFoundException%7CChecksumException%7CFormatException ex) %7B%0A            text = null
+    reason = null;%0A            qrd.reset();%0A        %7D catch(NotFoundException ex) %7B%0A            text = null;%0A            reason = %22QR Code not found. Extra info: %22 + ex.getMessage();%0A        %7D catch(ChecksumException ex) %7B%0A            text = null;%0A            reason = %22QR Code has invalid checksum. Extra info: %22 + ex.getMessage();%0A        %7D catch(FormatException ex) %7B%0A            text = null;%0A            reason = %22QR Code not properly formatted. Extra info: %22 + ex.getMessage()
 ;%0A  

Reset qrdetector periodically and added checksum failing reasons