/**
 * ESPromise.ts
 * @author  Nev Wylie (newylie))
 * @copyright Microsoft 2019
 * Simplified wrapper to provide ES6 style Promise callback handling for older browsers
 */

import { isFunction } from "@microsoft/applicationinsights-core-js";
import dynamicProto from "@microsoft/dynamicproto-js";

/**
 * @ignore -- Don't include in the generated documentation
 */
const enum PromiseState {
    Pending = 0,
    Resolved = 1,
    Rejected = 2
}

/**
 * @ignore -- Don't include in the generated documentation
 * Using a local variable to assist with minfication
 */
var _isFunction = isFunction;

/**
 * @ignore -- Don't include in the generated documentation
 * This function will be used as onFulfilled handler for any Promise found in the iterable passed to Promise.all.
 * The goal here is to capture in a closure the index of the current item from the iterable. If we did not create
 * this closure, the captured index variable would be the same one that the for loop updates and thus would always
 * be pointing to the last index in the iterable by the time that the onFulfilled handler is called.
 * However, note that for the resolvedCallback callback we want the opposite. For this one we do want to capture
 * the same variable that the for loop updates so that we have the full count of pending promises by the time
 * the onFulfilled handlers start getting called.
 * @param values The resolving promise values
 * @param index The index of this callback function
 * @param resolvedCallback THe callback function used to check if the "all" promise is complete
 */
function _createPromiseAllOnResolvedFunction(values: any[], index: number, resolvedCallback: VoidFunction) {
    return (value: any) => {
        values[index] = value;
        resolvedCallback();
    };
}

/**
 * This defines the handler function for when a promise is resolved.
 * @param value This is the value passed as part of resolving the Promise
 * @return This may return a value, another Promise or void. See [[then]] for how the value is handled.
 */
export type ESPromiseOnResolvedFunc<T> = (value: T) => T|ESPromise<T|any>|void;

/**
 * This defines the handler function for when a promise is rejected.
 * @param value This is the value passed as part of resolving the Promise
 * @return This may return a value, another Promise or void. @see then for how the value is handled.
 */
export type ESPromiseOnRejectedFunc<T> = (reason: any) => T|ESPromise<T|any>|void;

/**
 * Defines the signature of the resolve function passed to the resolverFunc (in the Promise constructor)
 * @param value The value to resolve the Promise with
 * @returns Nothing
 */
export type ResolverResolveFunc<T> = (value?: T|void) => void;

/**
 * Defines the signature of the reject function passed to the resolverFunc (in the Promise constructor)
 * @param value The value to reject the Promise with
 * @returns Nothing
 */
export type ResolverRejectFunc<T> = (reason?: T|Error|void) => void;

/**
 * Simplified wrapper to provide ES6 style Promise callback handling for older browsers
 */
export default class ESPromise<T> {

    /**
     * The Promise.resolve() method returns a Promise object that is resolved with a given value. If the value is a promise, that promise is returned;
     * if the value is a thenable (i.e. has a "then" method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise
     * the returned promise will be fulfilled with the value. This function flattens nested layers of promise-like objects (e.g. a promise that resolves
     * to a promise that resolves to something) into a single layer.
     * @param value Argument to be resolved by this Promise. Can also be a Promise or a thenable to resolve.
     */
    public static resolve<T>(value?: any) {
        if (value instanceof ESPromise) {
            // Value is a Promise so just return it
            return value;
        } else if (value && _isFunction(value.then)) {
            // Value looks like a promise or thenable (has a then function)
            return new ESPromise((resolve, reject) => {
                try {
                    value.then(resolve, reject);
                } catch (error) {
                    reject(error);
                }
            });
        }

        return new ESPromise<T>((resolve) => {
            resolve(value);
        });
    }

    /**
     * The Promise.reject() method returns a Promise object that is rejected with a given reason.
     * @param reason The reason why this Promise rejected.
     */
    public static reject<T>(reason?: T | Error | void) {
        return new ESPromise<T>((resolve, reject) => {
            reject(reason);
        });
    }

    /**
     * The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable
     * have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that
     * rejects. There is no implied ordering in the execution of the array of Promises given. On some computers, they
     * may be executed in parallel, or in some sense concurrently, while on others they may be executed serially. For
     * this reason, there must be no dependency in any Promise on the order of execution of the Promises.
     * This method can be useful for aggregating the results of multiple promises.
     * FulfillmentSection - The returned promise is fulfilled with an array containing all the values of the iterable
     * passed as argument (also non-promise values).
     * If an empty iterable is passed, then this method returns (synchronously) an already resolved promise.
     * If all of the passed-in promises fulfill, or are not promises, the promise returned by Promise.all is fulfilled
     * asynchronously.
     * RejectionSection - If any of the passed-in promises reject, Promise.all asynchronously rejects with the value of
     * the promise that rejected, whether or not the other promises have resolved.
     * @param iterable
     */
    public static all<T>(iterable: any[]) {
        if (!iterable || !iterable.length) {
            return;
        }

        return new ESPromise<T>((resolve, reject) => {
            try {
                let values = [] as any;
                let pending = 0;

                for (let lp = 0; lp < iterable.length; lp++) {
                    let item: any = iterable[lp];

                    // Quick and direct check for a Promise (will also catch a thenable)
                    if (item && _isFunction(item.then)) {
                        pending++;
                        item.then(
                            _createPromiseAllOnResolvedFunction(
                                values,
                                lp,
                                () => {
                                    if (--pending === 0) {
                                        resolve(values);
                                    }
                                }),
                            reject);
                    } else {
                        values[lp] = item;
                    }
                }

                if (pending === 0) {
                    // All promises were either resolved or where not a promise
                    setTimeout(() => {
                        resolve(values);
                    }, 0);
                }
            } catch (error) {
                reject(error);
            }
        });
    }

    /**
     * The race function returns a Promise that is settled the same way (and takes the same value) as the first promise
     * that settles amongst the promises of the iterable passed as an argument.
     * If the iterable passed is empty, the promise returned will be forever pending.
     * If the iterable contains one or more non-promise value and/or an already settled promise, then Promise.race will
     * resolve to the first of these values found in the iterable.
     * @param iterable
     */
    public static race<T>(iterable: any[]) {
        return new ESPromise<T>((resolve, reject) => {
            if (!iterable || !iterable.length) {
                return;
            }

            try {
                for (let lp = 0; lp < iterable.length; lp++) {
                    let item: any = iterable[lp];

                    // Quick and direct check for a Promise (will also catch a thenable)
                    if (item && _isFunction(item.then)) {
                        item.then(resolve, reject);
                    } else {
                        setTimeout(() => {
                            resolve(item);
                        }, 0);
                    }
                }
            } catch (error) {
                reject(error);
            }
        });
    }

    /**
     * The Promise object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.
     * @param resolverFunc A function that is passed with the arguments resolve and reject. The executor function is executed
     * immediately by the Promise implementation, passing resolve and reject functions (the executor is called before the Promise
     * constructor even returns the created object). The resolve and reject functions, when called, resolve or reject the promise,
     * respectively. The executor normally initiates some asynchronous work, and then, once that completes, either calls the resolve
     * function to resolve the promise or else rejects it if an error occurred. If an error is thrown in the executor function, the
     * promise is rejected. The return value of the executor is ignored.
     */
    constructor(resolverFunc: (resolve: ResolverResolveFunc<T>, reject: ResolverRejectFunc<T>) => void) {
        let _state = PromiseState.Pending;
        let _settledValue: T = null;
        let _queue = [];

        dynamicProto(ESPromise, this, (_this) => {
            _this.then = (onResolved: ESPromiseOnResolvedFunc<T>, onRejected?: ESPromiseOnRejectedFunc<T>) => {
                return new ESPromise((resolve: ResolverResolveFunc<T>, reject: ResolverRejectFunc<T>) => {
                    // Queue the new promise returned to be resolved or rejected
                    // when this promise settles.
                    _enqueue(onResolved, onRejected, resolve, reject);
                });
            };

            _this["catch"] = (onRejected: ESPromiseOnRejectedFunc<T>) => {
                return _this.then(null, onRejected);
            };
        });

        function _enqueue(onResolved: ESPromiseOnResolvedFunc<T>, onRejected: ESPromiseOnRejectedFunc<T>, resolve: ResolverResolveFunc<T>, reject: ResolverRejectFunc<T>) {
            _queue.push(() => {
                let value: T|ESPromise<T>|void;

                try {
                    // First call the onFulfilled or onRejected handler, on the settled value
                    // of this promise. If the corresponding handler does not exist, simply
                    // pass through the settled value.
                    if (_state === PromiseState.Resolved) {
                        value = _isFunction(onResolved) ? onResolved(_settledValue) : _settledValue;
                    } else {
                        value = _isFunction(onRejected) ? onRejected(_settledValue) : _settledValue;
                    }

                    if (value instanceof ESPromise) {
                        // The called handlers returned a new promise, so the chained promise
                        // will follow the state of this promise.
                        value.then(resolve, reject);
                    } else if (_state === PromiseState.Rejected && !_isFunction(onRejected)) {
                        // If there wasn't an onRejected handler and this promise is rejected, then
                        // the chained promise also rejects with the same reason.
                        reject(value);
                    } else {
                        // If this promise is fulfilled, then the chained promise is also fulfilled
                        // with either the settled value of this promise (if no onFulfilled handler
                        // was available) or the return value of the handler. If this promise is
                        // rejected and there was an onRejected handler, then the chained promise is
                        // fulfilled with the return value of the handler.
                        resolve(value);
                    }
                } catch (error) {
                    // The chained promise will reject if there is any exception thrown while
                    // calling the onFulfilled or onRejected handlers.
                    reject(error);
                    return;
                }
            });

            // If this promise is already settled, then immediately process the callback we
            // just added to the queue.
            if (_state !== PromiseState.Pending) {
                _processQueue();
            }
        }

        function _processQueue() {
            if (_queue.length > 0) {
                // The onFulfilled and onRejected handlers must be called asynchronously. Thus,
                // we make a copy of the queue and work on it once the current call stack unwinds.
                let pending = _queue.slice();
                _queue = [];

                setTimeout(() => {
                    for (var i = 0, len = pending.length; i < len; ++i) {
                        try {
                            pending[i]();
                        } catch (e) {
                            // Don't let 1 failing handler break all others
                            // TODO (newylie): Add some form of error reporting (i.e. Call any registered JS error handler so the error is reported)
                        }
                    }
                }, 0);
            }
        }

        function _resolve(value: T): void {
            if (_state === PromiseState.Pending) {
                _settledValue = value;
                _state = PromiseState.Resolved;
                _processQueue();
            }
        }

        function _reject(reason: any): void {
            if (_state === PromiseState.Pending) {
                _settledValue = reason;
                _state = PromiseState.Rejected;
                _processQueue();
            }
        }

        (function _initialize() {
            if (!_isFunction(resolverFunc)) {
                throw new TypeError("ESPromise: resolvedFunc argument is not a Function");
            }

            try {
                resolverFunc(_resolve, _reject);
            } catch (error) {
                // This promise will immediately reject if any exception is thrown
                // from within the executor function.
                _reject(error);
            }
        })();
    }

    /**
     * The then() method returns a Promise. It takes up to two arguments: callback functions for the success and failure cases of the Promise.
     * @param onResolved A Function called if the Promise is fulfilled. This function has one argument, the fulfillment value. If it is not a
     * function, it is internally replaced with an "Identity" function (it returns the received argument).
     * @param onRejected A Function called if the Promise is rejected. This function has one argument, the rejection reason. If it is not a
     * function, it is internally replaced with a "Thrower" function (it throws an error it received as argument).
     * @returns Once a Promise is fulfilled or rejected, the respective handler function (onFulfilled or onRejected) will be called asynchronously
     * (scheduled in the current thread loop). The behavior of the handler function follows a specific set of rules. If a handler function:
     * - returns a value, the promise returned by then gets resolved with the returned value as its value;
     * - doesn't return anything, the promise returned by then gets resolved with an undefined value;
     * - throws an error, the promise returned by then gets rejected with the thrown error as its value;
     * - returns an already fulfilled promise, the promise returned by then gets fulfilled with that promise's value as its value;
     * - returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value;
     * - returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the
     * resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.
     */
    public then(onResolved: ESPromiseOnResolvedFunc<T>, onRejected?: ESPromiseOnRejectedFunc<T>): ESPromise<T> {
        // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging
        return;
    }

    /**
     * The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.prototype.then(undefined, onRejected)
     * (in fact, calling obj.catch(onRejected) internally calls obj.then(undefined, onRejected)). This means that you have to provide an onRejected function
     * even if you want to fall back to an undefined result value - for example obj.catch(() => {}).
     * @param onRejected A Function called when the Promise is rejected. This function has one argument: reason The rejection reason.
     * @returns Internally calls Promise.prototype.then on the object upon which it was called, passing the parameters undefined and the received
     * onRejected handler. Returns the value of that call, which is a Promise.
     */
    public catch(onRejected: ESPromiseOnRejectedFunc<T>): ESPromise<T> {
        // @DynamicProtoStub - DO NOT add any code as this will be removed during packaging
        return;
    }
}
