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

"""
import random
import string
import qrcode
import qrcode.image.svg

from io import BytesIO


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

    Returns:
        token (str)
    """
    return generate_random_string(
        length=64,
        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(random.choice(elements) for i in range(length))
    return ret_val


def generate_qr_code(content: str, size: int = 20) -> str:
    """ Generates a qr code from given content

    Args:
        content (str): The content for the qr code
        size (int): The image size

    Returns:
        qrcode_svg (str): The qr code as svg
    """
    qrcode_factory = qrcode.image.svg.SvgImage
    qrcode_img = qrcode.make(
        content,
        image_factory=qrcode_factory,
        box_size=size
    )
    stream = BytesIO()
    qrcode_img.save(stream)
    return stream.getvalue().decode()
