import base64
import io

import qrcode
from PIL import Image, ImageDraw
from django.conf import settings


def get_certificate_qr_code(data: str):
    qr = qrcode.QRCode(
        version=12,
        error_correction=qrcode.constants.ERROR_CORRECT_H,
        box_size=8,
        border=1,
    )

    # To add data to the QR Code
    qr.add_data(data)
    qr.make()

    # You need to convert the image into RGB in order to use it
    img_qr = qr.make_image().convert('RGB')

    # Get logo with white background
    logo_path = settings.STATIC_COMPANIES / 'assets' / 'img' / 'dc-logo.png'
    logo = Image.open(logo_path)

    # Get hex dimensions
    w = logo.size[0]
    h = logo.size[1]
    s = h / 2
    o = (h - s) / 2
    hex_path = [
        (w / 2, h),
        (w, o + s),
        (w, o),
        (w / 2, 0),
        (0, o),
        (0, o + s),
    ]

    # Create a white hexagon
    white_hex = Image.new('RGBA', logo.size)
    d = ImageDraw.Draw(white_hex)
    d.polygon(hex_path, fill=(255, 255, 255, 255))

    # Get overlay position
    pos = ((img_qr.size[0] - w) // 2, (img_qr.size[1] - h) // 2)

    # Paste white hex and transparent logo over QR code
    img_qr.paste(white_hex, pos, mask=white_hex)
    img_qr.paste(logo, pos, mask=logo)

    # Create base64 image stream
    buffer = io.BytesIO()
    img_qr.save(buffer, 'PNG')
    img_str = base64.b64encode(buffer.getvalue()).decode()

    return img_str
