; (function (window) {
    window.DartAsyncCallHelper = DartAsyncCallHelper;
    function DartAsyncCallHelper() {
        this._callbacks = {};

        this.init = function () {
            window.dartCaller = this;
            window.dartCallback = function (id, data) {
                window.dartCaller.callback(id, data);
            };
        }

        this.callAsync = function (method, data) {
            var id = this._generateId();
            var that = this;
            return new Promise(function (resolve, reject) {
                that._record(id, function (data) {
                    resolve(data);
                });
                var message = {
                    method: method,
                    rid: id,
                    data: data,
                }
                window['Dart_AsyncCall'](message);
            });
        }

        this.callback = function (id, data) {
            var fn = this._callbacks[id];
            fn && fn(data);
            delete this._callbacks[id];
        }

        this._record = function (id, fn) {
            this._callbacks[id] = fn;
        }
        this._generateId = function () {
            var timestamp = Date.now();
            var suffix = Math.round(Math.random() * 1000).toString().padStart(3, '0');
            return timestamp + suffix;
        }
    }
})(window);