// #region Imports
import { directive, PartType } from 'lit/directive.js';
import { Signal } from '../../../Messaging/Signal';
import { AsyncDirectiveBase } from '../Abstracts/AsyncDirectiveBase';
// #endregion
class WhenSignalDirective extends AsyncDirectiveBase {
    // #region Fields
    _unsub;
    _condition;
    _trueTemplate;
    _falseTemplate;
    // #endregion
    // #region Ctor
    /**
     * Constructs a new instance of the `WhenSignalDirective` class.
     *
     * @public
     */
    constructor(args) {
        super(args);
        if (args.type !== PartType.CHILD) {
            throw new Error('whenSignal() can only be used in child bindings');
        }
    }
    // #endregion
    // public render<C extends Falsy, T, F = undefined>(condition: C | Signal<C>, trueCase: (c: C) => T, falseCase?: (c: C) => F): F;
    // public render<C, T, F>(condition: C extends Falsy ? never : C | Signal<C>, trueCase: (c: C) => T, falseCase?: (c: C) => F): T;
    // public render<C, T, F = undefined>(condition: C | Signal<C>, trueCase: (c: Exclude<C, Falsy>) => T, falseCase?: (c: Extract<C, Falsy>) => F): C extends Falsy ? F : T;
    render(condition, trueCase, falseCase) {
        return this.updateCondition(condition, trueCase, falseCase);
    }
    update(_, [condition, trueCase, falseCase]) {
        return this.updateCondition(condition, trueCase, falseCase);
    }
    disconnected() {
        super.disconnected();
        if (this._unsub) {
            this._unsub();
            this._unsub = undefined;
        }
    }
    reconnected() {
        super.reconnected();
        if (this._condition instanceof Signal) {
            this._unsub = this._condition.subscribe(() => this.notifySignalChanged());
        }
    }
    updateCondition(condition, trueCase, falseCase) {
        if (this._unsub) {
            this._unsub();
            this._unsub = undefined;
        }
        this._condition = condition;
        this._trueTemplate = trueCase;
        this._falseTemplate = falseCase;
        if (condition instanceof Signal) {
            this._unsub = condition.subscribe(() => this.notifySignalChanged());
        }
        return this.evaluate();
    }
    getCondition() {
        return typeof this._condition === 'boolean'
            ? this._condition
            : this._condition?.get() ?? false;
    }
    evaluate() {
        const condValue = this.getCondition();
        const callback = condValue ? this._trueTemplate : this._falseTemplate;
        const param = this._condition instanceof Signal ? this._condition.get() : this._condition;
        return callback?.(param);
    }
    notifySignalChanged() {
        this.setValue(this.evaluate());
    }
}
/**
 * @public
 */
export const when = directive(WhenSignalDirective);
//# sourceMappingURL=WhenDirective.js.map