# retoor <retoor@molodetz.nl>

import time
import requests
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from devplacepy.database import get_table
_counter_project_files = [0]
def _signup_project_files():
    _counter_project_files[0] += 1
    name = f"pf{int(time.time() * 1000)}{_counter_project_files[0]}"
    session = requests.Session()
    session.post(
        f"{BASE_URL}/auth/signup",
        data={
            "username": name,
            "email": f"{name}@t.dev",
            "password": "secret123",
            "confirm_password": "secret123",
            "birth_date": "1990-01-01",
            "accept_terms": "1",
        },
        allow_redirects=True,
    )
    key = get_table("users").find_one(username=name)["api_key"]
    return name, key
def _h_project_files(key):
    return {"X-API-KEY": key, "Accept": "application/json"}
def _create_project_project_files(key, title):
    r = requests.post(
        f"{BASE_URL}/projects/create",
        headers=_h_project_files(key),
        data={
            "title": title,
            "description": "filesystem test",
            "project_type": "software",
            "status": "In Development",
        },
    )
    assert r.status_code == 200, r.text
    return r.json()["data"]
def _write_project_files(key, slug, path, content):
    return requests.post(
        f"{BASE_URL}/projects/{slug}/files/write",
        headers=_h_project_files(key),
        data={"path": path, "content": content},
        allow_redirects=False,
    )
def _mkdir(key, slug, path):
    return requests.post(
        f"{BASE_URL}/projects/{slug}/files/mkdir",
        headers=_h_project_files(key),
        data={"path": path},
        allow_redirects=False,
    )
def _move(key, slug, from_path, to_path):
    return requests.post(
        f"{BASE_URL}/projects/{slug}/files/move",
        headers=_h_project_files(key),
        data={"from_path": from_path, "to_path": to_path},
        allow_redirects=False,
    )
def _delete(key, slug, path):
    return requests.post(
        f"{BASE_URL}/projects/{slug}/files/delete",
        headers=_h_project_files(key),
        data={"path": path},
        allow_redirects=False,
    )
def _list(slug, key=None):
    return requests.get(
        f"{BASE_URL}/projects/{slug}/files",
        headers=_h_project_files(key) if key else {"Accept": "application/json"},
    )
def _raw_project_files(slug, path, key=None):
    return requests.get(
        f"{BASE_URL}/projects/{slug}/files/raw",
        params={"path": path},
        headers=_h_project_files(key) if key else {"Accept": "application/json"},
    )
def _paths(slug, key=None):
    return sorted(f["path"] for f in _list(slug, key).json()["files"])
def _make_project_ui(page, title):
    page.goto(f"{BASE_URL}/projects", wait_until="domcontentloaded")
    page.locator("#create-project-btn").click()
    page.fill("#title", title)
    page.fill("#description", "Project for filesystem UI test")
    page.click("button:has-text('Create Project')")
    page.wait_for_url(f"{BASE_URL}/projects/*", wait_until="domcontentloaded")
    return page.url
def _open_files(page, title):
    proj_url = _make_project_ui(page, title)
    slug = proj_url.rstrip("/").split("/")[-1]
    page.goto(proj_url + "/files", wait_until="domcontentloaded")
    return slug
def _dialog_fill(page, value):
    page.locator(".dialog-overlay.visible .dialog-input").wait_for(state="visible")
    page.fill(".dialog-overlay.visible .dialog-input", value)
    page.click(".dialog-overlay.visible .dialog-confirm")
def _dialog_confirm(page):
    page.locator(".dialog-overlay.visible .dialog-confirm").wait_for(state="visible")
    page.click(".dialog-overlay.visible .dialog-confirm")
def _dialog_cancel(page):
    page.locator(".dialog-overlay.visible .dialog-cancel").wait_for(state="visible")
    page.click(".dialog-overlay.visible .dialog-cancel")
def _new_folder(page, name):
    page.click("#pf-new-folder")
    _dialog_fill(page, name)
    page.wait_for_selector(f".pf-node-row:has-text('{name.split('/')[-1]}')")
def _new_file(page, name):
    page.click("#pf-new-file")
    _dialog_fill(page, name)
def _row(page, name):
    return page.locator(f".pf-node-row:has-text('{name}')").first
def _alice_key():
    return get_table("users").find_one(username="alice_test")["api_key"]


def test_guest_write_blocked(app_server):
    _, key = _signup_project_files()
    slug = _create_project_project_files(key, "FS Guest")["slug"]
    r = requests.post(
        f"{BASE_URL}/projects/{slug}/files/write",
        data={"path": "x.py", "content": "1"},
        allow_redirects=False,
    )
    assert r.status_code in (303, 401)
    assert _paths(slug, key) == []
