import { extractErrorMsg } from "@ibgib/helper-gib/dist/helpers/utils-helper.mjs";
import { ROOT } from "@ibgib/ts-gib/dist/V1/constants.mjs";
import { GLOBAL_LOG_A_LOT } from "../../../core-constants.mjs";
import { isIbGib } from "../../other/ibgib-helper.mjs";
import { getErrorIbGib, isError } from "../../error/error-helper.mjs";
import { AnonymousFnWitness_V1 } from "../../../witness/anonymous-fn/anonymous-fn-v1.mjs";
const logalot = GLOBAL_LOG_A_LOT;
/**
 * Determines type of incoming `err` and pulls out the error msg accordingly.
 *
 * ## note on not using {@link extractErrorMsg}
 *
 * {@link extractErrorMsg} is in helper-gib, which despite the name, does not
 * contain ibgib-specific types. So we can't pass in an ibGib and have it
 * extract the error msg.
 *
 * @returns error msg from incoming err
 */
export function extractObsErrMsg({ err, }) {
    const lc = `[${extractObsErrMsg.name}]`;
    try {
        if (logalot) {
            console.log(`${lc} starting... (I: 96f8b767c50f24768ced7beebb291723)`);
        }
        if (isIbGib(err)) {
            let ibGib = err;
            if (!err.data) {
                throw new Error(`err isIbGib but err.data is false. (E: 151a6bab647c638c454fd277ac468f23)`);
            }
            if (isError({ ibGib: err })) {
                return err.data.raw;
            }
            else {
                // shouldn't get here because function signature but hey ynk
                throw new Error(`(UNEXPECTED) err isIbGib but not ErrorIbGib_V1? (E: 81c2283fad5db3485c6e9acedbda9723)`);
            }
        }
        else {
            return extractErrorMsg(err);
        }
    }
    catch (error) {
        console.error(`${lc} ${error.message}`);
        throw error;
    }
    finally {
        if (logalot) {
            console.log(`${lc} complete.`);
        }
    }
}
/**
 * this is meant to be a wrapper of non-ibgib-like lambdas.
 *
 * So you take normal, mostly non-ibgib anonymous lambdas (that do indeed
 * have ibgib's as their inputs/outputs) and you wrap it here to get an
 * {@link ObserverWitness} which is an actual witness ibGib.
 * @param observer with regularish lambdas in a javascript object (not an ibgib)
 * @returns observer ibgib witness with formal ibgib witness signatures and the other ibgib properties: `ib`, `gib`, `data`, `rel8ns`
 */
export function fnObs(observerOrFn) {
    const lc = `[${fnObs.name}]`;
    try {
        if (logalot) {
            console.log(`${lc} starting... (I: 3d2c3658a0fda83ece1f2b095a365823)`);
        }
        let observer;
        if (typeof observerOrFn === 'function') {
            observer = { next: observerOrFn, };
        }
        else {
            observer = observerOrFn;
        }
        if (!observer.next) {
            throw new Error(`observer.next required (typeof observerOrFn !== 'function') (E: da944e93b32ab5918f11751bcd651823)`);
        }
        const fnNext = async (ibGib) => {
            await observer.next(ibGib);
            return ROOT;
        };
        /**
         * no idea what im doing here really...making an anonymous ibgib
         * essentially, but not sure how the witness fn would actually be used.
         * @param ibGib coming down the pipe?
         * @returns `ROOT`
         */
        const fnWitness = async (ibGib) => {
            if (ibGib.ib === 'complete') {
                if (observer.complete) {
                    await observer.complete();
                }
            }
            else if (isError({ ibGib })) {
                if (observer.error) {
                    await observer.error(ibGib);
                }
            }
            else {
                await observer.next(ibGib);
            }
            return ROOT;
        };
        // I'm wrapping these in anonymous fn witnesses, but do I need to?
        let nextAnonFnWitness = new AnonymousFnWitness_V1(fnNext); // cast should not be necessary
        let witnessAnonFnWitness = new AnonymousFnWitness_V1(fnWitness); // cast should not be necessary
        // const observerWitness: SubjectWitness<T> = {
        const observerWitness = {
            ib: 'observer',
            witness: async (x) => await witnessAnonFnWitness.witness(x),
            next: async (x) => { await nextAnonFnWitness.witness(x); },
            // isComplete: false,
            // isErrored: false,
            // isCompleteOrErrored: false,
            // asObservable: () => { throw new Error(`asObservable not impl on anonymous fn witness (E: d127d1822dbd90e7134cef75e4e23c23)`); },
            // subscribe: () => { throw new Error(`subscribe not impl on anonymous fn witness (E: 11ce7903626e8d1c3d27dc28f1e5cd23)`); },
        };
        let fnError = observer.error ?? (async (error) => {
            let errorMsg;
            if (typeof error === 'string') {
                errorMsg = extractErrorMsg(error);
            }
            else if (!!error.ib) {
                // error ibgib
                if (isError({ ibGib: error })) {
                    errorMsg = extractErrorMsg(error.data.raw);
                }
                else {
                    throw new Error(`${lc} (UNEXPECTED) first off, observer.error is falsy. secondly, error came down pipeline and has an "ib" property but is not an ErrorIbGib_V1? (E: 0a2a46b9620b4a6a84c7ba1100da537b)`);
                }
            }
            else if (error instanceof Error) {
                errorMsg = extractErrorMsg(error);
            }
            else if (typeof error.message === 'string') {
                errorMsg = extractErrorMsg(error.message);
            }
            else {
                errorMsg = '[unknown thing came down pipe that ain\'t an error]';
            }
            console.error(`Error occurred but observer.error is falsy. error: ${errorMsg} (E: 822c60c7c4d542efacd5c2dea7e88062)`);
        });
        const errorAnonFnWitness = new AnonymousFnWitness_V1(async (x) => { fnError(x); return ROOT; });
        observerWitness.error = async (x) => {
            // if (observerWitness.isCompleteOrErrored) {
            //     console.warn(`${lc} observerWitness.error triggered but observerWitness already complete or errored. (W: 85f8426d70404208b721a9de2876bbc2)`)
            //     return; /* <<<< returns early */
            // } else {
            //     // do these before any more handling in case there is some problem.
            //     (observerWitness as any).isErrored = true;
            //     (observerWitness as any).isCompleteOrErrored = true;
            // }
            // coerce non-ibgib errors into ErrorIbGib_V1
            if (typeof x === 'string') {
                x = await getErrorIbGib({ rawMsg: x });
            }
            else if (x instanceof Error) {
                x = await getErrorIbGib({ rawMsg: x.message });
            }
            try {
                await errorAnonFnWitness.witness(x);
            }
            catch (anotherError) {
                if (observer.error) {
                    console.error(`${lc} there was another error when executing errorAnonFnWitness.witness (wrapper of caller's observer.error) trapping this. (E: 8fa3c4e633df4491a82951e3b677d9a9)`);
                }
                else {
                    console.error(`${lc} there was another error when executing errorAnonFnWitness.witness (caller's observer.error was falsy). trapping this. (E: f5ff2db0d762487287139a4175eb7689)`);
                }
            }
        };
        if (observer.complete) {
            let fnComplete = observer.complete;
            let completeAnonFnWitness = new AnonymousFnWitness_V1(async (_) => {
                await fnComplete();
                return ROOT;
            });
            observerWitness.complete = async () => {
                // (observerWitness as any).isComplete = true;
                // (observerWitness as any).isCompleteOrErrored = true;
                try {
                    await completeAnonFnWitness.witness(ROOT);
                }
                catch (error) {
                    console.error(`${lc} there was an error when executing completeAnonFnWitness (wrapper for observer.complete fn) error: ${extractErrorMsg(error)} (E: c9e61b08429e42c1b85d2215f735ba2f)`);
                }
            };
        }
        return observerWitness;
    }
    catch (error) {
        console.error(`${lc} ${error.message}`);
        throw error;
    }
    finally {
        if (logalot) {
            console.log(`${lc} complete.`);
        }
    }
}
//# sourceMappingURL=observer-helper.mjs.map