"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.genericTuple = exports.GenericTupleArbitrary = void 0;
const Stream_1 = require("../../stream/Stream");
const symbols_1 = require("../symbols");
const Arbitrary_1 = require("./definition/Arbitrary");
const Shrinkable_1 = require("./definition/Shrinkable");
class GenericTupleArbitrary extends Arbitrary_1.Arbitrary {
    constructor(arbs) {
        super();
        this.arbs = arbs;
        for (let idx = 0; idx !== arbs.length; ++idx) {
            const arb = arbs[idx];
            if (arb == null || arb.generate == null)
                throw new Error(`Invalid parameter encountered at index ${idx}: expecting an Arbitrary`);
        }
    }
    static makeItCloneable(vs, shrinkables) {
        vs[symbols_1.cloneMethod] = () => {
            const cloned = [];
            for (let idx = 0; idx !== shrinkables.length; ++idx) {
                cloned.push(shrinkables[idx].value);
            }
            GenericTupleArbitrary.makeItCloneable(cloned, shrinkables);
            return cloned;
        };
        return vs;
    }
    static wrapper(shrinkables) {
        let cloneable = false;
        const vs = [];
        for (let idx = 0; idx !== shrinkables.length; ++idx) {
            const s = shrinkables[idx];
            cloneable = cloneable || s.hasToBeCloned;
            vs.push(s.value);
        }
        if (cloneable) {
            GenericTupleArbitrary.makeItCloneable(vs, shrinkables);
        }
        return new Shrinkable_1.Shrinkable(vs, () => GenericTupleArbitrary.shrinkImpl(shrinkables).map(GenericTupleArbitrary.wrapper));
    }
    generate(mrng) {
        return GenericTupleArbitrary.wrapper(this.arbs.map((a) => a.generate(mrng)));
    }
    static shrinkImpl(value) {
        let s = Stream_1.Stream.nil();
        for (let idx = 0; idx !== value.length; ++idx) {
            s = s.join(value[idx].shrink().map((v) => value
                .slice(0, idx)
                .concat([v])
                .concat(value.slice(idx + 1))));
        }
        return s;
    }
    withBias(freq) {
        return new GenericTupleArbitrary(this.arbs.map((a) => a.withBias(freq)));
    }
}
exports.GenericTupleArbitrary = GenericTupleArbitrary;
function genericTuple(arbs) {
    return new GenericTupleArbitrary(arbs);
}
exports.genericTuple = genericTuple;
