// 模拟 DispatcherObject
class DispatcherObject {
    // 模拟 Dispatcher
    public dispatcher: {
        checkAccess: () => boolean;
        invoke: (callback: () => void) => void;
    };

    constructor() {
        this.dispatcher = {
            checkAccess: () => true, // 简单模拟，始终返回 true
            invoke: (callback) => {
                setTimeout(callback, 0); // 模拟在主线程执行
            },
        };
    }
}

// 扩展方法实现
class DispatcherObjectExtension {
    public static UIInvoke(target: DispatcherObject, method: (...args: any[]) => any): any {
        if (target.dispatcher.checkAccess()) {
            return method();
        } else {
            return new Promise((resolve) => {
                target.dispatcher.invoke(() => {
                    const result = method();
                    resolve(result);
                });
            });
        }
    }

    public static UIInvokeWithType<T>(target: DispatcherObject, method: (...args: any[]) => T): T | Promise<T> {
        if (target.dispatcher.checkAccess()) {
            return method();
        } else {
            return new Promise((resolve) => {
                target.dispatcher.invoke(() => {
                    const result = method();
                    resolve(result);
                });
            });
        }
    }

    public static UIInvokeAction(target: DispatcherObject, action: () => void): void | Promise<void> {
        if (target.dispatcher.checkAccess()) {
            action();
        } else {
            return new Promise((resolve) => {
                target.dispatcher.invoke(() => {
                    action();
                    resolve();
                });
            });
        }
    }
}

// 示例使用
const obj = new DispatcherObject();
const method = () => {
    console.log('Method executed');
    return 42;
};
const action = () => console.log('Action executed');

// 调用 UIInvoke
const result = DispatcherObjectExtension.UIInvoke(obj, method);
if (result instanceof Promise) {
    result.then((value) => console.log('Result:', value));
} else {
    console.log('Result:', result);
}

// 调用 UIInvokeWithType
const typedResult = DispatcherObjectExtension.UIInvokeWithType<number>(obj, method);
if (typedResult instanceof Promise) {
    typedResult.then((value) => console.log('Typed Result:', value));
} else {
    console.log('Typed Result:', typedResult);
}

// 调用 UIInvokeAction
const actionResult = DispatcherObjectExtension.UIInvokeAction(obj, action);
if (actionResult instanceof Promise) {
    actionResult.then(() => console.log('Action completed'));
} else {
    console.log('Action completed');
}
