const fileName_1 = "(@effect/core) _src/io/Schedule/operations/unionWith.ts";
import * as tsplus_module_1 from "@tsplus/stdlib/data/Tuple/make";
import * as tsplus_module_2 from "@tsplus/stdlib/data/Tuple/mergeTuple";
import * as tsplus_module_3 from "@effect/core/io/Schedule/Decision";
import * as tsplus_module_4 from "@effect/core/io/Effect/operations/zipWith";
import { makeWithState } from "@effect/core/io/Schedule/operations/_internal/makeWithState";
/**
 * Returns a new schedule that combines this schedule with the specified
 * schedule, continuing as long as either schedule wants to continue and
 * merging the next intervals according to the specified merge function.
 *
 * @tsplus fluent ets/Schedule unionWith
 * @tsplus fluent ets/Schedule/WithState unionWith
 */

export function unionWith_(self, that, f) {
  return makeWithState(tsplus_module_1.make(self._initial, that._initial), (now, input, state) => {
    const left = self._step(now, input, state.get(0));

    const right = that._step(now, input, state.get(1));

    return tsplus_module_4.zipWith_(left, () => right, ({
      tuple: [lState, l, lDecision]
    }, {
      tuple: [rState, r, rDecision]
    }) => {
      if (lDecision._tag === "Done" && rDecision._tag === "Done") {
        return tsplus_module_1.make(tsplus_module_1.make(lState, rState), tsplus_module_2.mergeTuple(l, r), tsplus_module_3.done);
      }

      if (lDecision._tag === "Done" && rDecision._tag === "Continue") {
        return tsplus_module_1.make(tsplus_module_1.make(lState, rState), tsplus_module_2.mergeTuple(l, r), tsplus_module_3._continue(rDecision.interval));
      }

      if (lDecision._tag === "Continue" && rDecision._tag === "Done") {
        return tsplus_module_1.make(tsplus_module_1.make(lState, rState), tsplus_module_2.mergeTuple(l, r), tsplus_module_3._continue(lDecision.interval));
      }

      if (lDecision._tag === "Continue" && rDecision._tag === "Continue") {
        const combined = f(lDecision.interval, rDecision.interval);
        return tsplus_module_1.make(tsplus_module_1.make(lState, rState), tsplus_module_2.mergeTuple(l, r), tsplus_module_3._continue(combined));
      }

      throw new Error("bug");
    }, fileName_1 + ":27:24");
  });
}
/**
 * Returns a new schedule that combines this schedule with the specified
 * schedule, continuing as long as either schedule wants to continue and
 * merging the next intervals according to the specified merge function.
 *
 * @tsplus static ets/Schedule/Aspects unionWith
 */

export const unionWith = (that, f) => self => unionWith_(self, that, f);
//# sourceMappingURL=unionWith.mjs.map