"""Various utility functions for testing."""
import gzip
from pathlib import Path

from playwright.sync_api import Page


def load_gpx_asset(filename: str) -> bytes:
    """Load a GPX test asset.

    This looks in the tests/assets/ folder, reads and unzips the file and
    returns its contents.

    :param filename: Name of the asset to load.
    :return: The content of the asset as bytes.
    """
    asset_dir = Path(__file__).parent / 'assets'
    test_file = asset_dir / filename
    with gzip.open(test_file, 'rb') as fobj:
        return fobj.read()


def extract_and_upload(page: Page, filename: str, tmp_path: Path):
    """Extracts the given test asset, fills in the upload form and presses
    upload.

    :param page: The playwright page on which to execute the actions.
    :param filename: The filename.
    :param tmp_path: The temporary path (as given by pytest).
    """
    gpx_data = load_gpx_asset(filename)
    gpx_path = tmp_path / "Upload.gpx"
    with open(gpx_path, "wb") as gpx_fobj:
        gpx_fobj.write(gpx_data)

    page.get_by_label("GPX file").set_input_files(gpx_path)

    page.locator(".bi-upload").click()