!(function () {
    function JsonRpcClient(options) {
        const host = options.host;
        this.host = host;
        this.call = async function (module, method, data) {
            const req = packageReqObj(method, data);
            const url = `${host}${module}`;
            try {
                const res = await $.post(url, JSON.stringify(req));
                if (res == null) {
                    throw new JsonRpcError(-1, "Network Error");
                }
                if (!!res.error) {
                    throw new JsonRpcError(res.error.code, res.error.message);
                }
                return res.result;
            } catch (error) {
                let e = error;
                if (!(e instanceof JsonRpcError)) {
                    e = new JsonRpcError(-1, "Network Error");
                }
                this.onError && this.onError(e);
                throw e;
            }
        }

        function packageReqObj(method, data) {
            return {
                "jsonrpc": "2.0",
                "id": generateUUID(),
                "method": method,
                "params": [data],
            };
        }
    }
    function JsonRpcError(code, message) {
        Error.apply(this, arguments);

        this.code = code;
        this.message = message;
    }
    JsonRpcError.prototype = Object.create(Error.prototype);

    window.JsonRpcClient = JsonRpcClient;
    window.JsonRpcError = JsonRpcError;
})();