# retoor <retoor@molodetz.nl>

import html
import json
import re
import requests
from tests.conftest import BASE_URL
from devplacepy.database import get_table
from devplacepy.docs_api import API_GROUPS
from devplacepy.utils import clear_user_cache
def _configs_by_id(text):
    configs = re.findall(r"data-config='(.*?)'", text, re.S)
    return {
        json.loads(html.unescape(cfg))["id"]: json.loads(html.unescape(cfg))
        for cfg in configs
    }


def test_docs_every_api_group_page_loads(app_server):
    for group in API_GROUPS:
        r = requests.get(f"{BASE_URL}/docs/{group['slug']}.html")
        if group.get("admin"):
            assert r.status_code == 404, group["slug"]
            continue
        assert r.status_code == 200, group["slug"]
        if group["endpoints"]:
            assert "data-api-tester" in r.text


def test_docs_download_markdown(app_server):
    r = requests.get(f"{BASE_URL}/docs/download.md")
    assert r.status_code == 200
    assert "text/markdown" in r.headers["content-type"]
    assert 'filename="devplace-docs.md"' in r.headers["content-disposition"]
    assert "# DevPlace Documentation" in r.text
    assert "/profile/search" in r.text
    assert "| Name | In |" in r.text
    assert "/admin/services/" not in r.text  # admin pages excluded for guests


def test_docs_download_includes_admin_pages_for_admin(seeded_db):
    users = get_table("users")
    bob = users.find_one(username="bob_test")
    assert "/admin/services/" not in requests.get(f"{BASE_URL}/docs/download.md").text
    users.update({"uid": bob["uid"], "role": "Admin"}, ["uid"])
    clear_user_cache(bob["uid"])
    try:
        admin = requests.get(
            f"{BASE_URL}/docs/download.md", headers={"X-API-KEY": bob["api_key"]}
        )
        assert "/admin/services/" in admin.text
    finally:
        users.update({"uid": bob["uid"], "role": "Member"}, ["uid"])
        clear_user_cache(bob["uid"])
