"""
helper functions to work with OATH TOTP (RFC6238) OTP's and YubiHSM
"""

# Copyright (c) 2016 Storedsafe AB
# Copyright (c) 2011 Yubico AB
# See the file COPYING for licence statement.

import datetime
import time
from pyhsm.oath_hotp import search_for_oath_code as search_hotp

__all__ = [
    # constants
    # functions
    'search_for_oath_code',
    # classes
]


def search_for_oath_code(hsm, key_handle, nonce, aead, user_code, interval=30,
                         tolerance=0):
    """
    Try to validate an OATH TOTP OTP generated by a token whose secret key is
    available to the YubiHSM through the AEAD.

    The parameter `aead' is either a string, or an instance of YHSM_GeneratedAEAD.

    Returns timecounter value on successful auth, and None otherwise.
    """

    # timecounter is the lowest acceptable value based on tolerance
    timecounter = timecode(datetime.datetime.now(), interval) - tolerance

    return search_hotp(
        hsm, key_handle, nonce, aead, timecounter, user_code, 1 + 2*tolerance)


def timecode(time_now, interval):
    """ make integer and divide by time interval of valid OTP """
    i = time.mktime(time_now.timetuple())
    return int(i / interval)
