"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RemoteRef = void 0;
const STRING_1 = require("../constant/STRING");
class RemoteRef {
    constructor(API, post) {
        this._unlisten = {};
        this._ref = {};
        this._api = API;
        this._post = post;
    }
    exec(data) {
        const { type, data: _data } = data;
        switch (type) {
            case STRING_1.GET:
                {
                    const { id, method, data: __data } = _data;
                    this._api[STRING_1.GET][method](__data, (data, err) => {
                        this._post({ type: STRING_1.GET, data: { id, data, err } });
                    });
                }
                break;
            case STRING_1.CALL:
                {
                    const { id, method, data: __data } = _data;
                    this._api[STRING_1.CALL][method](__data, (data, err) => {
                        this._post({ type: STRING_1.CALL, data: { id, data, err } });
                    });
                }
                break;
            case STRING_1.WATCH:
                {
                    const { id, method, data: __data } = _data;
                    const unlisten = this._api[STRING_1.WATCH][method](__data, (data, err) => {
                        this._post({ type: STRING_1.WATCH, data: { id, data, err } });
                    });
                    this._unlisten[id] = unlisten;
                }
                break;
            case STRING_1.UNWATCH:
                {
                    const { id } = _data;
                    const unlisten = this._unlisten[id];
                    if (unlisten) {
                        unlisten();
                        delete this._unlisten[id];
                    }
                }
                break;
            case STRING_1.REF:
                {
                    const { id, method, data: __data } = _data;
                    const ref = this._api[STRING_1.REF][method](__data);
                    if (!ref) {
                        return;
                    }
                    const remote_ref = new RemoteRef(ref, (data) => {
                        this._post({ type: STRING_1.REF, data: { id, data } });
                    });
                    this._ref[id] = remote_ref;
                }
                break;
            case STRING_1.REF_EXEC:
                {
                    const { id, data: __data } = _data;
                    const ref = this._ref[id];
                    if (!ref) {
                        break;
                    }
                    ref.exec(__data);
                }
                break;
            default:
                throw new Error('invalid remote API data type');
        }
    }
}
exports.RemoteRef = RemoteRef;
//# sourceMappingURL=RemoteRef.js.map