""" Various string IDs
"""

import os
import pickle
import base64
import hashlib
import autoparse.pattern as app
import autoparse.find as apf


def hash_string(obj, length, remove_char_lst=()):
    """ Build a hash string from an input string that has
        a desired number of characters
    """
    if isinstance(obj, str):
        obj_str = obj.encode('utf-8')
    else:
        obj_str = pickle.dumps(obj)

    dig = hashlib.md5(obj_str).digest()
    hsh = base64.urlsafe_b64encode(dig)
    hsh = hsh.decode('utf-8')
    for symb in remove_char_lst:
        hsh = hsh.replace(symb, '')

    return hsh[:length]


def random_string_identifier():
    """ generate a "unique" (=long-ish, random) identifier

    :returns: a random string
    :rtype: str
    """
    rsi = base64.urlsafe_b64encode(os.urandom(9)).decode("utf-8")
    return rsi


def is_random_string_identifier(sid):
    """ could this have been generated by `random_string_identifier()`?

    :param sid: string identifier
    :type sid: string
    :returns: is the pattern a random string
    :rtype: bool
    """
    sid_pattern = app.URLSAFE_CHAR * 12
    return apf.full_match(sid_pattern, sid)


if __name__ == '__main__':
    STR = 'c1-3(5)4(2)7-6/h4,6H,1-2H3'
    HSTR = hash_string(STR, 3)
    print(HSTR)
