package epson.scan.lib;

import android.content.Context;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

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) {
        this.mEscanLib = escanlib;
    }

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

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

    public boolean isCanceled() {
        return this.mCanceled;
    }
}
