package epson.scan.lib;

import android.content.Context;
import android.os.Handler;



public class CancelableFind {
    private static final Object sLock = new Object();
    private final String TAG = "CFind";
    private volatile boolean isFinishSearchScanner = false;
    private volatile boolean mCanceled = false;
    private escanLib mEscanLib;

    public void setEscanLib(escanLib escanlib) {
        mEscanLib = escanlib;
    }

    public int findScanner(@NonNull Context context, @Nullable Handler handler) {
        int escanWrapperFindScanner;
        if (mCanceled) {
            return 40;
        }
        synchronized (sLock) {
            isFinishSearchScanner = false;
            mEscanLib.setSearchStt(true);
            mEscanLib.resetIPAdressCheck();
            escanWrapperFindScanner = mEscanLib.escanWrapperFindScanner(60);
            mEscanLib.setSearchStt(false);
            mEscanLib.setJobDone(true);
            isFinishSearchScanner = true;
            if (escanWrapperFindScanner == -1051) {
                throw new IllegalStateException("escanWrapperFindScanner() returns ESCAN_ERR_LIB_NOT_INITIALIZED");
            }
        }
        return escanWrapperFindScanner;
    }

    public void cancel() {
        if (!this.isFinishSearchScanner) {
            isFinishSearchScanner = true;
            mCanceled = true;
            escanLib escanlib = mEscanLib;
            if (escanlib != null) {
                escanlib.setSearchStt(false);
                mEscanLib.escanWrapperCancelFindScanner();
            }
        }
    }

    public boolean isCanceled() {
        return mCanceled;
    }
}
