export const waitATimeToExecute = (func: () => void) => {
    (<any>window).timeId = setInterval(() => {
        if (new Date().getSeconds() % 10 === 0) {

            try {
                func();
            } catch (error) {
                console.error(error);
            }

            clearInterval((<any>window).timeId);
        }
    }, 1);
};

export const createMutex = () => {
    let token = true;
    return (f: any, g?: any) => {
        if (token) {
            token = false;
            try {
                f();
            } finally {
                token = true;
            }
        } else if (g !== undefined) {
            g();
        }
    };
};

export function $(selector: string) {
    return document.querySelector(selector) as HTMLElement;
}

export function g(key: any, obj: any) {
    (<any>window)[key] = obj;
}

export function clone<T = any> (obj: T): T {
    return JSON.parse(JSON.stringify(obj));
}

export function throttle(func: any, delay: number) {
    let timeoutId: string | number | NodeJS.Timeout | undefined;
    let lastExecutedTime = 0;

    return function () {
        const currentTime = Date.now();

        if (currentTime - lastExecutedTime < delay) {
            clearTimeout(timeoutId);

            timeoutId = setTimeout(() => {
                lastExecutedTime = currentTime;
                func();
            }, delay);
        } else {
            lastExecutedTime = currentTime;
            func();
        }
    };
}

export function randomColor() {
    const colors: string[] = ["#FF0000", "#00FF00", "#0000FF", "#FF00FF", "#00FFFF", "#FFA500", "#800080", "#008000", "#FFC0CB"];
    return colors[Math.floor(Math.random() * colors.length)];
}