/**
 * 比较常用的工具模块
 * @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();
}

/**
 * 拦截对象方法调用
 * 
 * @param handler 处理器需要手动调用一次`Reflect.apply(target, thisArg, argArray)`，执行原方法，否则原方法不会执行
 */
export function interceptMethodCall(obj: object, handler: (target: any, p: string | symbol, thisArg: any, argArray: any[]) => Promise<any>) {
    return new Proxy(obj, {
        get(target, p, receiver) {
            if (typeof target[p] !== 'function')
                return Reflect.get(target, p, receiver);

            return new Proxy(target[p], {
                apply: async (target, thisArg, argArray) => {
                    return await handler(target, p, thisArg, argArray);
                }
            });
        }
    });
}