import json
import subprocess

from pathlib import Path

import pytest

from sanic_routing import __version__ as __routing_version__

from sanic import __version__


def capture(command):
    proc = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        cwd=Path(__file__).parent,
    )
    try:
        out, err = proc.communicate(timeout=1)
    except subprocess.TimeoutExpired:
        proc.kill()
        out, err = proc.communicate()
    return out, err, proc.returncode


def starting_line(lines):
    for idx, line in enumerate(lines):
        if line.strip().startswith(b"Sanic v"):
            return idx
    return 0


def read_app_info(lines):
    for line in lines:
        if line.startswith(b"{") and line.endswith(b"}"):
            return json.loads(line)


@pytest.mark.parametrize(
    "appname",
    (
        "fake.server.app",
        "fake.server:app",
        "fake.server:create_app()",
        "fake.server.create_app()",
    ),
)
def test_server_run(appname):
    command = ["sanic", appname]
    out, err, exitcode = capture(command)
    lines = out.split(b"\n")
    firstline = lines[starting_line(lines) + 1]

    assert exitcode != 1
    assert firstline == b"Goin' Fast @ http://127.0.0.1:8000"


@pytest.mark.parametrize(
    "cmd",
    (
        (
            "--cert=certs/sanic.example/fullchain.pem",
            "--key=certs/sanic.example/privkey.pem",
        ),
        (
            "--tls=certs/sanic.example/",
            "--tls=certs/localhost/",
        ),
        (
            "--tls=certs/sanic.example/",
            "--tls=certs/localhost/",
            "--tls-strict-host",
        ),
    ),
)
def test_tls_options(cmd):
    command = ["sanic", "fake.server.app", *cmd, "-p=9999", "--debug"]
    out, err, exitcode = capture(command)
    assert exitcode != 1
    lines = out.split(b"\n")
    firstline = lines[starting_line(lines) + 1]
    assert firstline == b"Goin' Fast @ https://127.0.0.1:9999"


@pytest.mark.parametrize(
    "cmd",
    (
        ("--cert=certs/sanic.example/fullchain.pem",),
        (
            "--cert=certs/sanic.example/fullchain.pem",
            "--key=certs/sanic.example/privkey.pem",
            "--tls=certs/localhost/",
        ),
        ("--tls-strict-host",),
    ),
)