// Copyright (c) 2009-2026 SAP SE, All Rights Reserved
/**
 * @fileoverview utility to wrap every value into a native promise
 */

sap.ui.define([
    // sap.ushell.base is a bootstrap dependency!
    // Be careful when adding new dependencies
    "sap/base/Log"
], (
    Log
) => {
    "use strict";

    /**
     * Wraps any value in a promise.
     * Works with jQuery Deferred.
     * @param {*} vValue The value to wrap
     * @param {boolean} [bWrapDeferredResult=false] Whether to wrap the result of a jQuery Deferred in an array. This can be used when multiples values are expected.
     * @returns {Promise} The wrapped value
     */
    function promisify (vValue, bWrapDeferredResult) {
        if (typeof vValue === "object") {
            if (vValue.done) { // jQuery.Deferred
                return new Promise((resolve, reject) => {
                    vValue
                        .done((...args) => {
                            if (bWrapDeferredResult) {
                                resolve(args);
                                return;
                            }

                            if (args.length > 1) {
                                Log.warning("jQuery.Deferred provided multiple return values, but only single return values are supported!");
                            }
                            resolve(args[0]);
                        })
                        .fail(reject);
                });
            }
            if (vValue.then) { // native promise
                return vValue;
            }
        }
        return Promise.resolve(vValue);
    }

    return promisify;
});
