import { toDisposable, DisposableStore } from '../lifecycle.js';
import { autorun } from './autorun.js';
import { ConvenientObservable, BaseObservable, subtransaction, transaction, _setKeepObserved, _setRecomputeInitiallyAndOnChange, observableValue } from './base.js';
import { getFunctionName, DebugNameData } from './debugName.js';
import { derivedOpts, derived } from './derived.js';
function constObservable(value) {
    return ( new ConstObservable(value));
}
class ConstObservable extends ConvenientObservable {
    constructor(value) {
        super();
        this.value = value;
    }
    get debugName() {
        return ( this.toString());
    }
    get() {
        return this.value;
    }
    addObserver(observer) {
    }
    removeObserver(observer) {
    }
    toString() {
        return `Const: ${this.value}`;
    }
}
function observableFromPromise(promise) {
    const observable = observableValue('promiseValue', {});
    promise.then((value) => {
        observable.set({ value }, undefined);
    });
    return observable;
}
function observableFromEvent(event, getValue) {
    return ( new FromEventObservable(event, getValue));
}
class FromEventObservable extends BaseObservable {
    constructor(event, _getValue) {
        super();
        this.event = event;
        this._getValue = _getValue;
        this.hasValue = false;
        this.handleEvent = (args) => {
            const newValue = this._getValue(args);
            const oldValue = this.value;
            const didChange = !this.hasValue || oldValue !== newValue;
            if (didChange) {
                this.value = newValue;
                if (this.hasValue) {
                    subtransaction(FromEventObservable.globalTransaction, (tx) => {
                        for (const o of this.observers) {
                            tx.updateObserver(o, this);
                            o.handleChange(this, undefined);
                        }
                    }, () => {
                        const name = this.getDebugName();
                        return 'Event fired' + (name ? `: ${name}` : '');
                    });
                }
                this.hasValue = true;
            }
        };
    }
    getDebugName() {
        return getFunctionName(this._getValue);
    }
    get debugName() {
        const name = this.getDebugName();
        return 'From Event' + (name ? `: ${name}` : '');
    }
    onFirstObserverAdded() {
        this.subscription = this.event(this.handleEvent);
    }
    onLastObserverRemoved() {
        this.subscription.dispose();
        this.subscription = undefined;
        this.hasValue = false;
        this.value = undefined;
    }
    get() {
        if (this.subscription) {
            if (!this.hasValue) {
                this.handleEvent(undefined);
            }
            return this.value;
        }
        else {
            return this._getValue(undefined);
        }
    }
}
( (function(observableFromEvent) {
    observableFromEvent.Observer = FromEventObservable;
    function batchEventsGlobally(tx, fn) {
        let didSet = false;
        if (FromEventObservable.globalTransaction === undefined) {
            FromEventObservable.globalTransaction = tx;
            didSet = true;
        }
        try {
            fn();
        }
        finally {
            if (didSet) {
                FromEventObservable.globalTransaction = undefined;
            }
        }
    }
    observableFromEvent.batchEventsGlobally = batchEventsGlobally;
})(observableFromEvent || (observableFromEvent = {})));
function observableSignalFromEvent(debugName, event) {
    return ( new FromEventObservableSignal(debugName, event));
}
class FromEventObservableSignal extends BaseObservable {
    constructor(debugName, event) {
        super();
        this.debugName = debugName;
        this.event = event;
        this.handleEvent = () => {
            transaction((tx) => {
                for (const o of this.observers) {
                    tx.updateObserver(o, this);
                    o.handleChange(this, undefined);
                }
            }, () => this.debugName);
        };
    }
    onFirstObserverAdded() {
        this.subscription = this.event(this.handleEvent);
    }
    onLastObserverRemoved() {
        this.subscription.dispose();
        this.subscription = undefined;
    }
    get() {
    }
}
function observableSignal(debugNameOrOwner) {
    if (typeof debugNameOrOwner === 'string') {
        return ( new ObservableSignal(debugNameOrOwner));
    }
    else {
        return ( new ObservableSignal(undefined, debugNameOrOwner));
    }
}
class ObservableSignal extends BaseObservable {
    get debugName() {
        return ( new DebugNameData(this._owner, this._debugName, undefined)).getDebugName(this) ?? 'Observable Signal';
    }
    constructor(_debugName, _owner) {
        super();
        this._debugName = _debugName;
        this._owner = _owner;
    }
    trigger(tx, change) {
        if (!tx) {
            transaction(tx => {
                this.trigger(tx, change);
            }, () => `Trigger signal ${this.debugName}`);
            return;
        }
        for (const o of this.observers) {
            tx.updateObserver(o, this);
            o.handleChange(this, change);
        }
    }
    get() {
    }
}
function debouncedObservable2(observable, debounceMs) {
    let hasValue = false;
    let lastValue;
    let timeout = undefined;
    return observableFromEvent(cb => {
        const d = autorun(reader => {
            const value = observable.read(reader);
            if (!hasValue) {
                hasValue = true;
                lastValue = value;
            }
            else {
                if (timeout) {
                    clearTimeout(timeout);
                }
                timeout = setTimeout(() => {
                    lastValue = value;
                    cb();
                }, debounceMs);
            }
        });
        return {
            dispose() {
                d.dispose();
                hasValue = false;
                lastValue = undefined;
            },
        };
    }, () => {
        if (hasValue) {
            return lastValue;
        }
        else {
            return observable.get();
        }
    });
}
function wasEventTriggeredRecently(event, timeoutMs, disposableStore) {
    const observable = observableValue('triggeredRecently', false);
    let timeout = undefined;
    disposableStore.add(event(() => {
        observable.set(true, undefined);
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(() => {
            observable.set(false, undefined);
        }, timeoutMs);
    }));
    return observable;
}
function keepObserved(observable) {
    const o = ( new KeepAliveObserver(false, undefined));
    observable.addObserver(o);
    return toDisposable(() => {
        observable.removeObserver(o);
    });
}
_setKeepObserved(keepObserved);
function recomputeInitiallyAndOnChange(observable, handleValue) {
    const o = ( new KeepAliveObserver(true, handleValue));
    observable.addObserver(o);
    if (handleValue) {
        handleValue(observable.get());
    }
    else {
        observable.reportChanges();
    }
    return toDisposable(() => {
        observable.removeObserver(o);
    });
}
_setRecomputeInitiallyAndOnChange(recomputeInitiallyAndOnChange);
class KeepAliveObserver {
    constructor(_forceRecompute, _handleValue) {
        this._forceRecompute = _forceRecompute;
        this._handleValue = _handleValue;
        this._counter = 0;
    }
    beginUpdate(observable) {
        this._counter++;
    }
    endUpdate(observable) {
        this._counter--;
        if (this._counter === 0 && this._forceRecompute) {
            if (this._handleValue) {
                this._handleValue(observable.get());
            }
            else {
                observable.reportChanges();
            }
        }
    }
    handlePossibleChange(observable) {
    }
    handleChange(observable, change) {
    }
}
function derivedObservableWithCache(computeFn) {
    let lastValue = undefined;
    const observable = derived(reader => {
        lastValue = computeFn(reader, lastValue);
        return lastValue;
    });
    return observable;
}
function derivedObservableWithWritableCache(owner, computeFn) {
    let lastValue = undefined;
    const counter = observableValue('derivedObservableWithWritableCache.counter', 0);
    const observable = derived(owner, reader => {
        counter.read(reader);
        lastValue = computeFn(reader, lastValue);
        return lastValue;
    });
    return Object.assign(observable, {
        clearCache: (transaction) => {
            lastValue = undefined;
            counter.set(counter.get() + 1, transaction);
        },
    });
}
function mapObservableArrayCached(owner, items, map, keySelector) {
    let m = ( new ArrayMap(map, keySelector));
    const self = derivedOpts({
        debugReferenceFn: map,
        owner,
        onLastObserverRemoved: () => {
            m.dispose();
            m = ( new ArrayMap(map));
        }
    }, (reader) => {
        m.setItems(items.read(reader));
        return m.getItems();
    });
    return self;
}
class ArrayMap {
    constructor(_map, _keySelector) {
        this._map = _map;
        this._keySelector = _keySelector;
        this._cache = ( new Map());
        this._items = [];
    }
    dispose() {
        this._cache.forEach(entry => entry.store.dispose());
        this._cache.clear();
    }
    setItems(items) {
        const newItems = [];
        const itemsToRemove = ( new Set(( this._cache.keys())));
        for (const item of items) {
            const key = this._keySelector ? this._keySelector(item) : item;
            let entry = this._cache.get(key);
            if (!entry) {
                const store = ( new DisposableStore());
                const out = this._map(item, store);
                entry = { out, store };
                this._cache.set(key, entry);
            }
            else {
                itemsToRemove.delete(key);
            }
            newItems.push(entry.out);
        }
        for (const item of itemsToRemove) {
            const entry = this._cache.get(item);
            entry.store.dispose();
            this._cache.delete(item);
        }
        this._items = newItems;
    }
    getItems() {
        return this._items;
    }
}
export { FromEventObservable, KeepAliveObserver, constObservable, debouncedObservable2, derivedObservableWithCache, derivedObservableWithWritableCache, keepObserved, mapObservableArrayCached, observableFromEvent, observableFromPromise, observableSignal, observableSignalFromEvent, recomputeInitiallyAndOnChange, wasEventTriggeredRecently };
