"""Firebase Push ID generator.  Converted to Python from
   https://gist.github.com/mikelehen/3596a30bd69384624c11
"""
import random
import time

PUSH_CHARS = '-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz'
_last_push_time = 0
_last_rand = []


def generate_pushid():
    """Generate a Firebase Push ID.  Converted this algorithm to Python:
       https://gist.github.com/mikelehen/3596a30bd69384624c11"""
    global _last_push_time, _last_rand
    now = int(time.time() * 1000)
    dup_time = (now == _last_push_time)
    _last_push_time = now

    tsc = [0] * 8
    for i in range(7, -1, -1):
        tsc[i] = PUSH_CHARS[now % 64]
        now = int(now / 64)
    assert now == 0
    if dup_time:
        for i in range(11, -1, -1):
            if _last_rand[i] == 63:
                _last_rand[i] = 0
            else:
                _last_rand[i] += 1
                break
    else:
        _last_rand = [random.randint(0, 63) for i in range(12)]

    tsc.extend([PUSH_CHARS[x] for x in _last_rand])
    return ''.join(tsc)
