"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 09.11.20

"""
import secrets
import string


def generate_token(length: int = 64) -> str:
    """ Shortcut for default generating of e.g. API token

    Returns:
        token (str)
    """
    return generate_random_string(
        length=length,
        use_numbers=True,
        use_letters_lc=True
    )


def generate_random_string(length: int, use_numbers: bool = False, use_letters_lc: bool = False, use_letters_uc: bool = False) -> str:
    """
    Generates a random string of variable length
    """
    elements = []
    if use_numbers:
        elements.append(string.digits)
    if use_letters_lc:
        elements.append(string.ascii_lowercase)
    if use_letters_uc:
        elements.append(string.ascii_uppercase)

    elements = "".join(elements)
    ret_val = "".join(secrets.choice(elements) for i in range(length))
    return ret_val

class IdentifierGenerator:
    _MODEL = None

    def __init__(self, model):
        from konova.models import BaseObject
        if not issubclass(model, BaseObject):
            raise AssertionError("Model must be a subclass of BaseObject!")

        self._MODEL = model

    def generate_id(self) -> str:
        """ Generates a unique identifier

        Returns:

        """
        unpersisted_object = self._MODEL()
        identifier = unpersisted_object.generate_new_identifier()
        while self._MODEL.objects.filter(identifier=identifier).exists():
            identifier = unpersisted_object.generate_new_identifier()
        return identifier
