import {
    useRef
} from "react";

interface IUseKey {
    removeKey(key: string): void;
    generateKey(): string;
}

const keyGenerator = (): string => {
    return `portalize_${Math.random().toString(36).substr(2, 16)}-${Math.random()
        .toString(36)
        .substr(2, 16)}-${Math.random().toString(36).substr(2, 16)}`;
};

export const useKey = (): IUseKey => {
    const usedKeys = useRef<Array<string>>([]);

    const generateKey = (): string => {
        let foundUniqueKey = false;
        let newKey = "";
        let tries = 0;

        while (!foundUniqueKey && tries < 3) {
            tries++;
            newKey = keyGenerator();

            if (!usedKeys.current.includes(newKey)) {
                foundUniqueKey = true;
            }
        }

        if (!foundUniqueKey) {
            newKey = `portalize_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
        }

        usedKeys.current.push(newKey);
        return newKey;
    };

    const removeKey = (key: string): void => {
        usedKeys.current = usedKeys.current.filter(k => k !== key);
    };

    return {
        generateKey,
        removeKey
    };
};
