
export const useUtilsStore = defineStore("utils_store", () => {

    /**
     * Valida el tiempo de expiracion de un jwt
     * @param token
     * @returns
     */
    const isExpiredToken = (token: string): number => {
        const payload_base64 = token.split('.')[1];
        const payload_json = JSON.parse(atob(payload_base64));

        const current_timestamp = new Date().getTime() / 1000;
        const token_is_not_expired = payload_json.exp > current_timestamp;

        const time_remaining =
            Math.floor((payload_json.exp - current_timestamp) * 0.8) * 1000;

        if (token_is_not_expired) {
            return time_remaining;
        } else {
            return 0;
        }
    }

    const validateOnlyNumber = (evt: KeyboardEvent) => {
        const input = evt.target as HTMLInputElement;
        const charCode = evt.which ? evt.which : evt.keyCode;
      
        // Permitir teclas de control como backspace
        if (charCode === 8) {
          return;
        }
      
        // Prevenir más entradas si la longitud del valor es 10
        if (input.value.length >= 10) {
          evt.preventDefault();
          return;
        }
      
        // Permitir solo números y un punto decimal
        if ((charCode > 31 && (charCode < 48 || charCode > 57)) && charCode !== 46) {
          evt.preventDefault();
        }
    }

    return {
        isExpiredToken,
        validateOnlyNumber,
    }
})