
import '../../errors.js';
import { strictEquals } from '../../equals.js';
import '../../event.js';
import { DisposableStore } from '../../lifecycle.js';
import { DebugNameData } from '../debugName.js';
import { _setDerivedOpts } from './baseObservable.js';
import { Derived, DerivedWithSetter } from './derivedImpl.js';

function derived(computeFnOrOwner, computeFn) {
    if (computeFn !== undefined) {
        return ( new Derived(( new DebugNameData(computeFnOrOwner, undefined, computeFn)), computeFn, undefined, undefined, strictEquals));
    }
    return ( new Derived(( new DebugNameData(undefined, undefined, computeFnOrOwner)), computeFnOrOwner, undefined, undefined, strictEquals));
}
function derivedWithSetter(owner, computeFn, setter) {
    return ( new DerivedWithSetter(( new DebugNameData(owner, undefined, computeFn)), computeFn, undefined, undefined, strictEquals, setter));
}
function derivedOpts(options, computeFn) {
    return ( new Derived(( new DebugNameData(options.owner, options.debugName, options.debugReferenceFn)), computeFn, undefined, options.onLastObserverRemoved, options.equalsFn ?? strictEquals));
}
_setDerivedOpts(derivedOpts);
function derivedHandleChanges(options, computeFn) {
    return ( new Derived(( new DebugNameData(options.owner, options.debugName, undefined)), computeFn, options.changeTracker, undefined, options.equalityComparer ?? strictEquals));
}
function derivedDisposable(computeFnOrOwner, computeFnOrUndefined) {
    let computeFn;
    let owner;
    if (computeFnOrUndefined === undefined) {
        computeFn = computeFnOrOwner;
        owner = undefined;
    }
    else {
        owner = computeFnOrOwner;
        computeFn = computeFnOrUndefined;
    }
    let store = undefined;
    return ( new Derived(( new DebugNameData(owner, undefined, computeFn)), r => {
        if (!store) {
            store = ( new DisposableStore());
        }
        else {
            store.clear();
        }
        const result = computeFn(r);
        if (result) {
            store.add(result);
        }
        return result;
    }, undefined, () => {
        if (store) {
            store.dispose();
            store = undefined;
        }
    }, strictEquals));
}

export { derived, derivedDisposable, derivedHandleChanges, derivedOpts, derivedWithSetter };
