
declare global {
    type PromiseExecutor<T> = (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void;
    type IPromiseFunc<T = any> = (executor: PromiseExecutor<T>) => Promise<T>;
}

/**
 * Resolved 的 Promise
 */
export const PromiseResolved = Promise.resolve();

/**
 * 在组件上挂载一个延迟的回调函数
 * @param seconds 延迟多少秒
 * @param comp 调度者
 * @param promise 
 * @returns 
 */
export const PromiseSchedulerSeconds = (seconds: number, comp: cc.Component, promise: IPromiseFunc = PromiseDefault) => {
    return promise(resolve => {
        comp.scheduleOnce(resolve, seconds);
    });
}

/**
 * TimeOutPromise
 * @param seconds 延迟多少秒
 * @param comp 调度者
 * @param promise 
 * @returns 
 */
export const PromiseTimeout = (seconds: number, func: (seconds) => void, promise: IPromiseFunc = PromiseDefault) => {
    return promise(resolve => {
        setTimeout(() => {
            func && func(seconds);
            resolve();
        }, seconds * 1000);
    });
}


/**
 * 默认的 Promise
 * @param executor 
 * @returns 
 */
export function PromiseDefault<T = any>(executor: PromiseExecutor<T>): Promise<T> {
    return new Promise(executor);
}

/**
 * 下一帧 resolve
 */
export function NextFrameResolvePromise(comp: cc.Component, curFrameFunc: () => void) {
    curFrameFunc();
    return new Promise(resolve => comp.scheduleOnce(resolve, 0))
}

/** 返回一个 interval 检测的 Promise */
export function IntervalCheckPromise(check: () => boolean, interval: number = 0.1) {
    return new Promise<void>(rs => {
        let timer;
        timer = setInterval(() => {
            if (check()) {
                clearInterval(timer);
                timer = null;
                rs();
            }
        }, interval * 1000);
    });
}