import { EventEmitter } from '@kano/common/index.js';
export class Instrument {
    constructor(fullPath, root, method) {
        this._onDidMethodCall = new EventEmitter();
        this.fullPath = fullPath;
        this.root = root;
        this.method = method;
        this.setup();
    }
    get onDidMethodCall() { return this._onDidMethodCall.event; }
    setup() {
        const parts = this.method.split('.');
        let { root } = this;
        let name;
        while (parts.length) {
            name = parts.shift();
            if (name && typeof root[name] === 'function') {
                this.methodParent = root;
                this.methodName = name;
                this.originalFunc = root[name];
                root[name] = this.callMethod(this.originalFunc);
                return;
            }
            if (name && typeof root[name] !== 'object') {
                throw new Error(`Could not intrumentize '${this.method}': path does not point to a function`);
            }
            root = name ? root[name] : root;
        }
        throw new Error(`Could not intrumentize '${this.method}'`);
    }
    callMethod(originalFunc) {
        return (...args) => {
            this._onDidMethodCall.fire({ method: this.fullPath, args });
            if (originalFunc) {
                return originalFunc(...args);
            }
        };
    }
    dispose() {
        if (!this.methodParent || !this.methodName) {
            return;
        }
        this.methodParent[this.methodName] = this.originalFunc;
    }
}
//# sourceMappingURL=instrument.js.map