"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.makeSingleProducerAsyncInput = exports.SingleProducerAsyncInput = exports.StateEmit = exports.EmitTypeId = exports.StateEmpty = exports.EmptyTypeId = exports.StateError = exports.ErrorTypeId = exports.StateDone = exports.DoneTypeId = void 0;
// ets_tracing: off
require("../../../../Operator");
const Cause = __importStar(require("../../../../Cause"));
const Tp = __importStar(require("../../../../Collections/Immutable/Tuple"));
const T = __importStar(require("../../../../Effect"));
const E = __importStar(require("../../../../Either"));
const Exit = __importStar(require("../../../../Exit"));
const P = __importStar(require("../../../../Promise"));
const Ref = __importStar(require("../../../../Ref"));
const IQ = __importStar(require("../../../../Support/ImmutableQueue"));
exports.DoneTypeId = Symbol();
class StateDone {
    constructor(a) {
        this.a = a;
        this._typeId = exports.DoneTypeId;
    }
}
exports.StateDone = StateDone;
exports.ErrorTypeId = Symbol();
class StateError {
    constructor(cause) {
        this.cause = cause;
        this._typeId = exports.ErrorTypeId;
    }
}
exports.StateError = StateError;
exports.EmptyTypeId = Symbol();
class StateEmpty {
    constructor(notifyProducer) {
        this.notifyProducer = notifyProducer;
        this._typeId = exports.EmptyTypeId;
    }
}
exports.StateEmpty = StateEmpty;
exports.EmitTypeId = Symbol();
class StateEmit {
    constructor(notifyConsumers) {
        this.notifyConsumers = notifyConsumers;
        this._typeId = exports.EmitTypeId;
    }
}
exports.StateEmit = StateEmit;
/**
 * An MVar-like abstraction for sending data to channels asynchronously. Designed
 * for one producer and multiple consumers.
 *
 * Features the following semantics:
 * - Buffer of size 1
 * - When emitting, the producer waits for a consumer to pick up the value
 *   to prevent "reading ahead" too much.
 * - Once an emitted element is read by a consumer, it is cleared from the buffer, so that
 *   at most one consumer sees every emitted element.
 * - When sending a done or error signal, the producer does not wait for a consumer
 *   to pick up the signal. The signal stays in the buffer after being read by a consumer,
 *   so it can be propagated to multiple consumers.
 * - Trying to publish another emit/error/done after an error/done have already been published
 *   results in an interruption.
 */
class SingleProducerAsyncInput {
    constructor(ref) {
        this.ref = ref;
        this.take = this.takeWith((c) => Exit.halt(Cause.map_(c, E.left)), (el) => Exit.succeed(el), (d) => Exit.fail(E.right(d)));
        this.close = T.chain_(T.fiberId, (id) => this.error(Cause.interrupt(id)));
        this.awaitRead = T.flatten(Ref.modify_(this.ref, (state) => {
            if (state._typeId === exports.EmptyTypeId) {
                return Tp.tuple(P.await(state.notifyProducer), state);
            }
            return Tp.tuple(T.unit, state);
        }));
    }
    emit(el) {
        return T.chain_(P.make(), (p) => T.flatten(Ref.modify_(this.ref, (state) => {
            switch (state._typeId) {
                case exports.EmitTypeId: {
                    const dequeued = state.notifyConsumers.dequeue();
                    if (dequeued._tag === "Some") {
                        const { tuple: [notifyConsumer, notifyConsumers] } = dequeued.value;
                        return Tp.tuple(P.succeed_(notifyConsumer, E.right(el)), notifyConsumers.size === 0
                            ? new StateEmpty(p)
                            : new StateEmit(notifyConsumers));
                    }
                    throw new Error("SingleProducerAsyncInput#emit: queue was empty");
                }
                case exports.ErrorTypeId: {
                    return Tp.tuple(T.interrupt, state);
                }
                case exports.DoneTypeId: {
                    return Tp.tuple(T.interrupt, state);
                }
                case exports.EmptyTypeId: {
                    return Tp.tuple(P.await(state.notifyProducer), state);
                }
            }
        })));
    }
    done(a) {
        return T.chain_(P.make(), (p) => T.flatten(Ref.modify_(this.ref, (state) => {
            switch (state._typeId) {
                case exports.EmitTypeId: {
                    return Tp.tuple(T.forEachUnit_(state.notifyConsumers, (p) => P.succeed_(p, E.left(a))), new StateDone(a));
                }
                case exports.ErrorTypeId: {
                    return Tp.tuple(T.interrupt, state);
                }
                case exports.DoneTypeId: {
                    return Tp.tuple(T.interrupt, state);
                }
                case exports.EmptyTypeId: {
                    return Tp.tuple(P.await(state.notifyProducer), state);
                }
            }
        })));
    }
    error(cause) {
        return T.chain_(P.make(), (p) => T.flatten(Ref.modify_(this.ref, (state) => {
            switch (state._typeId) {
                case exports.EmitTypeId: {
                    return Tp.tuple(T.forEachUnit_(state.notifyConsumers, (p) => P.halt_(p, cause)), new StateError(cause));
                }
                case exports.ErrorTypeId: {
                    return Tp.tuple(T.interrupt, state);
                }
                case exports.DoneTypeId: {
                    return Tp.tuple(T.interrupt, state);
                }
                case exports.EmptyTypeId: {
                    return Tp.tuple(P.await(state.notifyProducer), state);
                }
            }
        })));
    }
    takeWith(onError, onElement, onDone) {
        return T.chain_(P.make(), (p) => T.flatten(Ref.modify_(this.ref, (state) => {
            switch (state._typeId) {
                case exports.EmitTypeId: {
                    return Tp.tuple(T.foldCause_(P.await(p), onError, E.fold(onDone, onElement)), new StateEmit(state.notifyConsumers.push(p)));
                }
                case exports.ErrorTypeId: {
                    return Tp.tuple(T.succeed(onError(state.cause)), state);
                }
                case exports.DoneTypeId: {
                    return Tp.tuple(T.succeed(onDone(state.a)), state);
                }
                case exports.EmptyTypeId: {
                    return Tp.tuple(T.zipRight_(P.succeed_(state.notifyProducer, undefined), T.foldCause_(P.await(p), onError, E.fold(onDone, onElement))), new StateEmit(IQ.ImmutableQueue.single(p)));
                }
            }
        })));
    }
}
exports.SingleProducerAsyncInput = SingleProducerAsyncInput;
/**
 * Creates a SingleProducerAsyncInput
 */
function makeSingleProducerAsyncInput() {
    return T.map_(T.chain_(P.make(), (p) => Ref.makeRef(new StateEmpty(p))), (ref) => new SingleProducerAsyncInput(ref));
}
exports.makeSingleProducerAsyncInput = makeSingleProducerAsyncInput;
//# sourceMappingURL=producer.js.map