package com.iotize.plugin.cordova.zebrarfid;

import androidx.annotation.NonNull;

import com.zebra.rfid.api3.LOCK_DATA_FIELD;
import com.zebra.rfid.api3.LOCK_PRIVILEGE;
import com.zebra.rfid.api3.MEMORY_BANK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

class ArgsHelper {
    private final JSONObject args;

    public ArgsHelper(@NonNull JSONObject args) {
        this.args = args;
    }

    public static ArgsHelper fromCordovaCallParameters(JSONArray args) throws JSONException {
        JSONObject obj = null;
        if (args.length() > 0) {
            try {
                obj= args.getJSONObject(0);
            } catch (JSONException ex) {
                // Ok value is null or not an object
            }
        }
        return new ArgsHelper(obj == null ? new JSONObject() : obj);
    }

    public String getString(String name) {
        try {
            return this.args.getString(name);
        } catch (JSONException e) {
            //throw new PluginError(PluginError.Code.ILLEGAL_ARGUMENT, "Argument n°" + name + " must be a string");
            return null;
        }
    }

    public Integer getInt(String name) {
        try {
            return this.args.getInt(name);
        } catch (JSONException e) {
            //throw new PluginError(PluginError.Code.ILLEGAL_ARGUMENT, "Argument n°" + name + " must be a int");
            return null;
        }
    }

    public MEMORY_BANK getMemoryBank(String name) throws PluginError {
        return DataConverter.getMemoryBankFromOrdinal(this.getInt(name));
    }

    public LOCK_PRIVILEGE getLockPrivilege(String name) throws Exception {
        return DataConverter.getLockPrivilegeFromOrdinal(this.getInt(name));
    }

    public LOCK_DATA_FIELD getLockDataField(String name) throws Exception {
        return DataConverter.getDataFieldFromOrdinal(this.getInt(name));
    }

    public Boolean getBool(String name) {
        try {
            return this.args.getBoolean(name);
        } catch (JSONException e) {
            return null;
            // throw new PluginError(PluginError.Code.ILLEGAL_ARGUMENT, "Argument n°" + name + " must be a boolean");
        }
    }

    public Long getPassword(String key) {
        return DataConverter.getAccessPassword(this.getString(key));
    }

    public String getBytes(String hexString) {
        return DataConverter.getHexStringWithPadding(hexString);
    }
}
