# retoor <retoor@molodetz.nl>

import time

import requests

from devplacepy.database import get_table, refresh_snapshot
from tests.conftest import BASE_URL

JSON = {"Accept": "application/json"}
_counter_battles = [0]


def _session_battles():
    _counter_battles[0] += 1
    name = f"war{int(time.time() * 1000)}{_counter_battles[0]}"
    s = requests.Session()
    s.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,
    )
    return s, name


def _create_war_post(session, title, faction_a="Tabs", faction_b="Spaces"):
    r = session.post(
        f"{BASE_URL}/posts/create",
        data={
            "content": "Opinion War host post content for tests.",
            "title": title,
            "topic": "question",
            "war_faction_a": faction_a,
            "war_faction_b": faction_b,
        },
        allow_redirects=False,
    )
    slug = r.headers["location"].split("/posts/")[-1]
    refresh_snapshot()
    post = get_table("posts").find_one(slug=slug)
    war = get_table("opinion_wars").find_one(post_uid=post["uid"])
    return post, war


def _war_row(war_uid):
    refresh_snapshot()
    return get_table("opinion_wars").find_one(uid=war_uid)


def _fighter_row(war_uid, user_uid):
    refresh_snapshot()
    return get_table("opinion_war_fighters").find_one(
        war_uid=war_uid, user_uid=user_uid
    )


def _user_row(username):
    refresh_snapshot()
    return get_table("users").find_one(username=username)


def _join(session, war_uid, faction):
    return session.post(
        f"{BASE_URL}/battles/{war_uid}/join",
        data={"faction": faction},
        headers=JSON,
    )


def _fight(session, war_uid):
    return session.post(f"{BASE_URL}/battles/{war_uid}/fight", headers=JSON)
