#############################################################################
# Some helpers to make step functions simpler.

import logging
import os
import random
import shutil
import urllib.parse

import yaml


# Write a file with given content.
def _write(filename, content):
    open(filename, "w").write(content)


# Construct a URL that points to server running on localhost by
# replacing the actual scheme and host with ones that work for test.
def _url(ctx, url):
    listen = ctx["config"]["listen"]
    c = urllib.parse.urlparse(url)
    host = c[1]
    c = (c[0], "{}".format(listen)) + c[2:]
    return urllib.parse.urlunparse(c), host


#############################################################################
# The actual step functions.


# Fail: use this for unimplemented steps.
def fixme(*args, **kwargs):
    assert 0


# Create a directory.
def create_directory(ctx, dirname=None):
    dirname = "./" + dirname
    if not os.path.exists(dirname):
        os.makedirs(dirname)


# Copy test certificate from source tree, where it's been created previously by
# ./check.
def copy_test_certificate(ctx, cert=None, key=None):
    srcdir = globals()["srcdir"]
    logging.debug(f"Copying test.pem, test.key from srcdir to {cert} and {key}")
    shutil.copy(os.path.join(srcdir, "test.pem"), cert)
    shutil.copy(os.path.join(srcdir, "test.key"), key)


# Start server using named configuration file.
def start_server(ctx, filename=None):
    get_file = globals()["get_file"]
    srcdir = globals()["srcdir"]
    daemon_start_on_port = globals()["daemon_start_on_port"]

    logging.debug(f"Starting ewww with config file {filename}")
    config = get_file(filename).decode("UTF-8")
    config = yaml.safe_load(config)
    port = random.randint(2000, 30000)
    logging.debug(f"Picked randomly port for ewww: {port}")
    config["listen"] = f"localhost:{port}"
    ctx["config"] = config
    logging.debug(f"ewww config: {config!r}")
    config = yaml.safe_dump(config)
    _write(filename, config)

    target = os.environ.get("CARGO_TARGET_DIR", os.path.join(srcdir, "target"))
    logging.debug(f"Cargo target directory: {target}")
    binary = os.path.join(target, "debug", "ewww")
    daemon_start_on_port(ctx, binary, args=filename, name="ewww", port=port)


# Stop previously started server.
def stop_server(ctx, filename=None):
    daemon_stop = globals()["daemon_stop"]
    logging.debug("Stopping ewww")
    daemon_stop(ctx, name="ewww")


# Make an HTTP request.
def request(ctx, method=None, url=None):
    http_request = globals()["http_request"]
    logging.debug(f"Making HTTP request to ewww: {method} {url}")
    url, host = _url(ctx, url)
    http_request(ctx, host=host, method=method, url=url)
