import qrcode
import urllib.parse
from io import BytesIO


def create_login_url(base_uri: str, room_id: int, pin: int | None) -> str:
    parsed = urllib.parse.urlparse(base_uri)

    params = {
        "room": room_id,
    }

    if pin is not None:
        params["pin"] = pin

    parsed = parsed._replace(path="join", query=urllib.parse.urlencode(params))

    return urllib.parse.urlunparse(parsed)


def generate_qr(base_uri: str, room_id: int, pin: int | None) -> BytesIO:
    url = create_login_url(base_uri, room_id, pin)

    qr = qrcode.make(url)

    out = BytesIO()

    qr.save(out, format="jpeg")

    out.seek(0)

    return out
