package cordova.plugin.documentreader;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;

import android.util.Base64;

import com.regula.documentreader.api.completions.IDocumentReaderCompletion;
import com.regula.documentreader.api.completions.IDocumentReaderInitCompletion;
import com.regula.documentreader.api.completions.IDocumentReaderPrepareCompletion;
import com.regula.documentreader.api.enums.DocReaderAction;
import com.regula.documentreader.api.params.ImageInputParam;
import com.regula.documentreader.api.params.rfid.PKDCertificate;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import static java.util.Objects.requireNonNull;

public class DocumentReader extends CordovaPlugin {
    private CallbackContext callbackContext;
    private Context context;
    private static int databaseDownloadProgress = 0;

    private Context getContext() {
        return context;
    }

    private interface SuccessCallback {
        void callback(String success);
    }

    private interface ErrorCallback {
        void callback(String error);
    }

    static class JSONWrapper {
        JSONArray data;

        public JSONWrapper(JSONArray array) {
            data = array;
        }

        @Nullable
        public <T> T argument(String key) throws JSONException {
            //noinspection unchecked
            return (T) data.get(Integer.parseInt(key));
        }
    }

    private void sendProgress(int progress){
        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, "Downloading database: " + progress + "%");
        pluginResult.setKeepCallback(true);
        callbackContext.sendPluginResult(pluginResult);
    }

    @Override
    public boolean execute(String action, JSONArray args, CallbackContext result) {
        this.callbackContext = result;
        context = cordova.getActivity();
        JSONWrapper input = new JSONWrapper(args);

        try {
            switch (action) {
                case "getAvailableScenarios":
                    getAvailableScenarios(result::success);
                    break;
                case "getAPIVersion":
                    getAPIVersion(result::success);
                    break;
                case "getCoreVersion":
                    getCoreVersion(result::success);
                    break;
                case "getCoreMode":
                    getCoreMode(result::success);
                    break;
                case "getDatabaseID":
                    getDatabaseID(result::success);
                    break;
                case "getDatabaseVersion":
                    getDatabaseVersion(result::success);
                    break;
                case "getDatabaseDate":
                    getDatabaseDate(result::success);
                    break;
                case "getDatabaseDescription":
                    getDatabaseDescription(result::success);
                    break;
                case "getDatabaseCountriesNumber":
                    getDatabaseCountriesNumber(result::success);
                    break;
                case "getDatabaseDocumentsNumber":
                    getDatabaseDocumentsNumber(result::success);
                    break;
                case "getScenario":
                    getScenario(result::success, input.argument("0"));
                    break;
                case "isRFIDAvailableForUse":
                    isRFIDAvailableForUse(result::success);
                    break;
                case "getDocumentReaderIsReady":
                    getDocumentReaderIsReady(result::success);
                    break;
                case "getDocumentReaderStatus":
                    getDocumentReaderStatus(result::success);
                    break;
                case "selectedScenario":
                    selectedScenario(result::success);
                    break;
                case "getSessionLogFolder":
                    getSessionLogFolder(result::success);
                    break;
                case "initializeReader":
                    initializeReader(result::success, result::error, input.argument("0"));
                    break;
                case "prepareDatabase":
                    prepareDatabase(result::success, result::error, input.argument("0"));
                    break;
                case "recognizeImage":
                    recognizeImage(result::success, result::error, input.argument("0"));
                    break;
                case "recognizeImageFrame":
                    recognizeImageFrame(result::success, result::error, input.argument("0"), input.argument("1"));
                    break;
                case "recognizeImageWithOpts":
                    recognizeImageWithOpts(result::success, result::error, input.argument("0"), input.argument("1"));
                    break;
                case "recognizeVideoFrame":
                    recognizeVideoFrame(result::success, result::error, input.argument("0"), input.argument("1"));
                    break;
                case "runAutoUpdate":
                    runAutoUpdate(result::success, result::error, input.argument("0"));
                    break;
                case "setConfig":
                    setConfig(result::success, input.argument("0"));
                    break;
                case "setCameraSessionIsPaused":
                    setCameraSessionIsPaused(result::error, requireNonNull(input.argument("0")));
                    break;
                case "readRFID":
                    readRFID(result::error);
                    break;
                case "setRfidScenario":
                    setRfidScenario(result::success, input.argument("0"));
                    break;
                case "showScanner":
                    showScanner(result::success, result::error);
                    break;
                case "showScannerWithCameraID":
                    showScannerWithCameraID(result::success, result::error, requireNonNull(input.argument("0")));
                    break;
                case "showScannerWithCameraIDAndOpts":
                    showScannerWithCameraIDAndOpts(result::success, result::error, requireNonNull(input.argument("0")), input.argument("1"));
                    break;
                case "startNewPage":
                    startNewPage(result::success);
                    break;
                case "startNewSession":
                    startNewSession(result::success);
                    break;
                case "startRFIDReader":
                    startRFIDReader(result::success, result::error);
                    break;
                case "stopRFIDReader":
                    stopRFIDReader(result::success);
                    break;
                case "stopScanner":
                    stopScanner(result::success);
                    break;
                case "deinitializeReader":
                    deinitializeReader(result::success);
                    break;
                case "isAuthenticatorAvailableForUse":
                    isAuthenticatorAvailableForUse(result::success);
                    break;
                case "getConfig":
                    getConfig(result::success);
                    break;
                case "getRfidScenario":
                    getRfidScenario(result::success);
                    break;
                case "getLicenseExpiryDate":
                    getLicenseExpiryDate(result::success, result::error);
                    break;
                case "getLicenseCountryFilter":
                    getLicenseCountryFilter(result::success, result::error);
                    break;
                case "licenseIsRfidAvailable":
                    licenseIsRfidAvailable(result::success);
                    break;
                case "recognizeImageWithImageInputParams":
                    recognizeImageWithImageInputParams(result::success, result::error, input.argument("0"), input.argument("1"));
                    break;
                case "recognizeImages":
                    recognizeImages(result::success, result::error, input.argument("0"));
                    break;
                case "removeDatabase":
                    removeDatabase(result::success);
                    break;
                case "cancelDBUpdate":
                    cancelDBUpdate(result::success);
                    break;
                case "resetConfiguration":
                    resetConfiguration(result::success);
                    break;
                case "setEnableCoreLogs":
                    setEnableCoreLogs(result::success, requireNonNull(input.argument("0")));
                    break;
                case "addPKDCertificates":
                    addPKDCertificates(result::success, requireNonNull(input.argument("0")));
                    break;
                case "clearPKDCertificates":
                    clearPKDCertificates(result::success);
                    break;
                case "permissionRead":
                    permissionRead(result::success, result::error);
                    break;
            }
        } catch (Exception ignored) {
        }
        return true;
    }

    public void getAvailableScenarios(SuccessCallback successCallback) throws JSONException {
        successCallback.callback(JSONConstructor.generateList(com.regula.documentreader.api.DocumentReader.Instance().availableScenarios, JSONConstructor::generateDocumentReaderScenario, getContext()).toString());
    }

    public void getAPIVersion(SuccessCallback successCallback) {
        successCallback.callback(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).api);
    }

    public void getCoreVersion(SuccessCallback successCallback) {
        successCallback.callback(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).core);
    }

    public void getCoreMode(SuccessCallback successCallback) {
        successCallback.callback(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).coreMode);
    }

    public void getDatabaseID(SuccessCallback successCallback) {
        successCallback.callback(requireNonNull(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).database).databaseID);
    }

    public void getDatabaseVersion(SuccessCallback successCallback) {
        successCallback.callback(requireNonNull(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).database).version);
    }

    public void getDatabaseDate(SuccessCallback successCallback) {
        successCallback.callback(requireNonNull(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).database).date);
    }

    public void getDatabaseDescription(SuccessCallback successCallback) {
        successCallback.callback(requireNonNull(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).database).databaseDescription);
    }

    public void getDatabaseCountriesNumber(SuccessCallback successCallback) {
        successCallback.callback("" + requireNonNull(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).database).countriesNumber);
    }

    public void getDatabaseDocumentsNumber(SuccessCallback successCallback) {
        successCallback.callback("" + requireNonNull(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().version).database).documentsNumber);
    }

    public void deinitializeReader(SuccessCallback successCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().deinitializeReader();
        successCallback.callback("");
    }

    public void isAuthenticatorAvailableForUse(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().isAuthenticatorAvailableForUse() ? "1" : "0");
    }

    public void getConfig(SuccessCallback successCallback) throws JSONException {
        successCallback.callback(RegulaConfig.getConfig(com.regula.documentreader.api.DocumentReader.Instance(), getContext()).toString());
    }

    public void getRfidScenario(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().rfidScenario().toJson());
    }

    public void selectedScenario(SuccessCallback successCallback) throws JSONException {
        successCallback.callback(JSONConstructor.generateDocumentReaderScenario(com.regula.documentreader.api.DocumentReader.Instance().getScenario(com.regula.documentreader.api.DocumentReader.Instance().processParams().getScenario())).toString());
    }

    public void getScenario(SuccessCallback successCallback, String scenario) throws JSONException {
        successCallback.callback(JSONConstructor.generateDocumentReaderScenario(com.regula.documentreader.api.DocumentReader.Instance().getScenario(scenario)).toString());
    }

    public void getLicenseExpiryDate(SuccessCallback successCallback, ErrorCallback errorCallback) {
        if (com.regula.documentreader.api.DocumentReader.Instance().license().getExpiryDate() == null)
            errorCallback.callback("null");
        else
            successCallback.callback(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().license().getExpiryDate()).toString());
    }

    public void getLicenseCountryFilter(SuccessCallback successCallback, ErrorCallback errorCallback) {
        if (com.regula.documentreader.api.DocumentReader.Instance().license().getCountryFilter() == null)
            errorCallback.callback("null");
        else
            successCallback.callback(JSONConstructor.generateList(requireNonNull(com.regula.documentreader.api.DocumentReader.Instance().license().getCountryFilter())).toString());
    }

    public void licenseIsRfidAvailable(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().license().isRfidAvailable() ? "1" : "0");
    }

    public void getDocumentReaderIsReady(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady() ? "1" : "0");
    }

    public void getDocumentReaderStatus(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderStatus());
    }

    public void isRFIDAvailableForUse(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().isRFIDAvailableForUse() ? "1" : "0");
    }

    private void initializeReader(SuccessCallback successCallback, ErrorCallback errorCallback, Object license) {
        if (!com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady())
            com.regula.documentreader.api.DocumentReader.Instance().initializeReader(getContext(), Base64.decode(license.toString(), Base64.DEFAULT), getInitCompletion(successCallback, errorCallback));
        else
            successCallback.callback("already initialized");
    }

    public void startNewSession(SuccessCallback successCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().startNewSession();
        successCallback.callback("");
    }

    public void startNewPage(SuccessCallback successCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().startNewPage();
        successCallback.callback("");
    }

    public void recognizeImageWithImageInputParams(SuccessCallback successCallback, ErrorCallback errorCallback, String base64Image, final JSONObject params) throws JSONException {
        if (com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady())
            com.regula.documentreader.api.DocumentReader.Instance().recognizeImage(JSONConstructor.bitmapFromBase64(base64Image), new ImageInputParam(params.getInt("width"), params.getInt("height"), params.getInt("type")), getCompletion(successCallback, errorCallback));
        else
            errorCallback.callback("document reader not ready");
    }

    public void recognizeImageWithOpts(SuccessCallback successCallback, ErrorCallback errorCallback, final JSONObject opts, String base64Image) throws JSONException {
        RegulaConfig.setConfig(com.regula.documentreader.api.DocumentReader.Instance(), opts, getContext());
        recognizeImage(successCallback, errorCallback, base64Image);
    }

    public void recognizeImage(SuccessCallback successCallback, ErrorCallback errorCallback, String base64Image) {
        if (com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady())
            com.regula.documentreader.api.DocumentReader.Instance().recognizeImage(JSONConstructor.bitmapFromBase64(base64Image), getCompletion(successCallback, errorCallback));
        else
            errorCallback.callback("document reader not ready");
    }

    public void recognizeImages(SuccessCallback successCallback, ErrorCallback errorCallback, JSONArray base64Images) throws JSONException {
        if (com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady()) {
            Bitmap[] images = new Bitmap[base64Images.length()];
            for (int i = 0; i < images.length; i++)
                images[i] = JSONConstructor.bitmapFromBase64(base64Images.getString(i));
            com.regula.documentreader.api.DocumentReader.Instance().recognizeImages(images, getCompletion(successCallback, errorCallback));
        } else
            errorCallback.callback("document reader not ready");
    }

    public void removeDatabase(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().removeDatabase(getContext()) ? "1" : "0");
    }

    public void cancelDBUpdate(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().cancelDBUpdate() ? "1" : "0");
    }

    public void resetConfiguration(SuccessCallback successCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().resetConfiguration();
        successCallback.callback("");
    }

    public void setEnableCoreLogs(SuccessCallback successCallback, boolean enableLogs) {
        com.regula.documentreader.api.DocumentReader.Instance().setEnableCoreLogs(enableLogs);
        successCallback.callback("");
    }

    public void addPKDCertificates(SuccessCallback successCallback, JSONArray certificatesJSON) throws JSONException {
        List<PKDCertificate> certificates = new ArrayList<>();
        for (int i = 0; i < certificatesJSON.length(); i++) {
            JSONObject certificate = certificatesJSON.getJSONObject(i);
            certificates.add(new PKDCertificate(JSONConstructor.byteArrayFromJson(certificate.getJSONArray("binaryData")), certificate.getInt("resourceType"), certificate.has("certificate") ? JSONConstructor.byteArrayFromJson(certificate.getJSONArray("privateKey")) : null));
        }
        com.regula.documentreader.api.DocumentReader.Instance().addPKDCertificates(certificates);
        successCallback.callback("");
    }

    public void clearPKDCertificates(SuccessCallback successCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().clearPKDCertificates();
        successCallback.callback("");
    }

    public void recognizeImageFrame(SuccessCallback successCallback, ErrorCallback errorCallback, String base64Image, final JSONObject opts) throws JSONException {
        if (com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady())
            com.regula.documentreader.api.DocumentReader.Instance().recognizeImageFrame(JSONConstructor.bitmapFromBase64(base64Image), new ImageInputParam(opts.getInt("width"), opts.getInt("height"), opts.getInt("type")), getCompletion(successCallback, errorCallback));
        else
            errorCallback.callback("document reader not ready");
    }

    public void recognizeVideoFrame(SuccessCallback successCallback, ErrorCallback errorCallback, String byteString, final JSONObject opts) throws JSONException {
        if (com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady())
            com.regula.documentreader.api.DocumentReader.Instance().recognizeVideoFrame(byteString.getBytes(), new ImageInputParam(opts.getInt("width"), opts.getInt("height"), opts.getInt("type")), getCompletion(successCallback, errorCallback));
        else
            errorCallback.callback("document reader not ready");
    }

    public void showScannerWithCameraID(SuccessCallback successCallback, ErrorCallback errorCallback, int cameraID) {
        if (com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady())
            com.regula.documentreader.api.DocumentReader.Instance().showScanner(getContext(), cameraID, getCompletion(successCallback, errorCallback));
        else
            errorCallback.callback("document reader not ready");
    }

    public void showScanner(SuccessCallback successCallback, ErrorCallback errorCallback) {
        showScannerWithCameraID(successCallback, errorCallback, -1);
    }

    public void showScannerWithCameraIDAndOpts(SuccessCallback successCallback, ErrorCallback errorCallback, int cameraID, final JSONObject opts) throws JSONException {
        if (com.regula.documentreader.api.DocumentReader.Instance().getDocumentReaderIsReady()) {
            RegulaConfig.setConfig(com.regula.documentreader.api.DocumentReader.Instance(), opts, getContext());
            com.regula.documentreader.api.DocumentReader.Instance().showScanner(getContext(), cameraID, getCompletion(successCallback, errorCallback));
        } else
            errorCallback.callback("document reader not ready");
    }

    public void stopScanner(SuccessCallback successCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().stopScanner(getContext());
        successCallback.callback("");
    }

    public void startRFIDReader(SuccessCallback successCallback, ErrorCallback errorCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().startRFIDReader(getContext(), getCompletion(successCallback, errorCallback));
    }

    public void stopRFIDReader(SuccessCallback successCallback) {
        com.regula.documentreader.api.DocumentReader.Instance().stopRFIDReader(getContext());
        successCallback.callback("");
    }

    public void prepareDatabase(SuccessCallback successCallback, ErrorCallback errorCallback, String dbID) {
        com.regula.documentreader.api.DocumentReader.Instance().prepareDatabase(getContext(), dbID, getPrepareCompletion(successCallback, errorCallback));
    }

    public void runAutoUpdate(SuccessCallback successCallback, ErrorCallback errorCallback, String dbID) {
        com.regula.documentreader.api.DocumentReader.Instance().runAutoUpdate(getContext(), dbID, getPrepareCompletion(successCallback, errorCallback));
    }

    public void setRfidScenario(SuccessCallback successCallback, final JSONObject opts) throws JSONException {
        RegulaConfig.setRfidScenario(opts);
        successCallback.callback("");
    }

    public void getSessionLogFolder(SuccessCallback successCallback) {
        successCallback.callback(com.regula.documentreader.api.DocumentReader.Instance().processParams().sessionLogFolder);
    }

    public void setConfig(SuccessCallback successCallback, final JSONObject opts) throws JSONException {
        RegulaConfig.setConfig(com.regula.documentreader.api.DocumentReader.Instance(), opts, getContext());
        successCallback.callback("");
    }

    public void setCameraSessionIsPaused(ErrorCallback errorCallback, @SuppressWarnings("unused") boolean ignored) {
        errorCallback.callback("setCameraSessionIsPaused() is an ios-only method");
    }
    
    public void readRFID(ErrorCallback errorCallback) {
        errorCallback.callback("readRFID() is an ios-only method");
    }

    public void permissionRead(SuccessCallback successCallback, ErrorCallback errorCallback) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != 0) {
            ActivityCompat.requestPermissions((Activity) getContext(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            errorCallback.callback("no permission");
        } else
            successCallback.callback("");
    }

    private IDocumentReaderCompletion getCompletion(SuccessCallback successCallback, ErrorCallback errorCallback) {
        return (action, results, error) -> {
            switch (action) {
                case DocReaderAction.COMPLETE:
                    successCallback.callback(JSONConstructor.resultsToJsonObject(results, getContext()).toString());
                    break;
                case DocReaderAction.CANCEL:
                    errorCallback.callback("Canceled by user");
                    break;
                case DocReaderAction.ERROR:
                    errorCallback.callback("Error: " + error);
                    break;
            }
        };
    }

    private IDocumentReaderPrepareCompletion getPrepareCompletion(SuccessCallback successCallback, ErrorCallback errorCallback) {
        return new IDocumentReaderPrepareCompletion() {
            @Override
            public void onPrepareProgressChanged(int progress) {
                if (progress != databaseDownloadProgress) {
                    sendProgress(progress);
                    databaseDownloadProgress = progress;
                }
            }

            @Override
            public void onPrepareCompleted(boolean status, String error) {
                if (status)
                    successCallback.callback("database prepared");
                else
                    errorCallback.callback("database preparation failed: " + error);
            }
        };
    }

    private IDocumentReaderInitCompletion getInitCompletion(SuccessCallback successCallback, ErrorCallback errorCallback) {
        return (success, error) -> {
            if (success)
                successCallback.callback("init completed");
            else
                errorCallback.callback("Init failed:" + error);
        };
    }
}