/**
 * 比较常用的工具模块
 * @date 2022-03
 * @author 何华东
 */

import { v4 as uuidv4 } from 'uuid';

/**
 * 替换所有字符串, 某些特殊字符不支持，例如：`\\n`
 */
export function replaceAll(value: string, searchValue: string, replaceValue: string) {
    if (!value || !searchValue || !replaceValue) return value;

    //replace(/'/g, "/'");
    return value.replace(new RegExp(searchValue, 'g'), replaceValue);
}

/**
 * 生成一个`uuid`
 */
export function uuid() {
    return uuidv4();
}

/**
 * 拦截对象方法调用
 */
export function interceptMethodCall(obj: object, handler: (thisArg: any, methodName: string | symbol, next: Function) => Promise<any>) {
    return new Proxy(obj, {
        get(target, p, receiver) {
            if (typeof target[p] === 'function') {
                return new Proxy(target[p], {
                    apply: async (target, thisArg, argArray) => {
                        let res = null;
                        await handler(thisArg, p, () => { res = Reflect.apply(target, thisArg, argArray); });
                        return res;
                    }
                });
            }

            return Reflect.get(target, p, receiver);
        }
    });
}