# retoor <retoor@molodetz.nl>

import re
from datetime import datetime, timezone
from playwright.sync_api import expect
from tests.conftest import BASE_URL
from devplacepy.database import get_table
from devplacepy.utils import generate_uid, make_combined_slug

GIVE_AWARD_BTN = "[data-award-give]"
AWARD_MODAL = "#award-give-modal"
AWARD_TEXTAREA = "#award-give-modal textarea[name='description']"
AWARDS_TAB = "a.profile-tab[href*='tab=awards']"
AWARD_BADGE = ".award-badge"


def _seed_published(receiver_username, giver_username, description="E2E award"):
    receiver = get_table("users").find_one(username=receiver_username)
    giver = get_table("users").find_one(username=giver_username)
    uid = generate_uid()
    slug = make_combined_slug(description, uid)
    now = datetime.now(timezone.utc).isoformat()
    get_table("awards").insert(
        {
            "uid": uid,
            "slug": slug,
            "description": description,
            "giver_uid": giver["uid"],
            "receiver_uid": receiver["uid"],
            "attachment_uid_512": "",
            "attachment_uid_256": "",
            "attachment_uid_64": "",
            "generated_at": now,
            "created_at": now,
            "job_uid": "",
            "deleted_at": None,
            "deleted_by": None,
        }
    )
    get_table("users").update(
        {
            "uid": receiver["uid"],
            "award_count": 1,
            "last_award_at": now,
            "last_award_slug": slug,
            "last_award_uid": uid,
        },
        ["uid"],
    )
    return slug


def test_give_award_button_visible_on_other_profile(alice):
    page, user = alice
    page.goto(f"{BASE_URL}/profile/bob_test", wait_until="domcontentloaded")
    if page.is_visible(GIVE_AWARD_BTN):
        expect(page.locator(GIVE_AWARD_BTN)).to_be_visible()
    page.goto(f"{BASE_URL}/profile/{user['username']}", wait_until="domcontentloaded")
    expect(page.locator(GIVE_AWARD_BTN)).to_have_count(0)


def test_award_modal_char_counter_and_submit_dialog(alice):
    page, _ = alice
    page.goto(f"{BASE_URL}/profile/bob_test", wait_until="domcontentloaded")
    if not page.is_visible(GIVE_AWARD_BTN):
        return
    page.click(GIVE_AWARD_BTN)
    expect(page.locator(AWARD_MODAL)).to_have_class(re.compile(r"\bvisible\b"))
    page.fill(AWARD_TEXTAREA, "x" * 125)
    expect(page.locator("[data-award-char-count]")).to_contain_text("125/125")
    page.locator(f"{AWARD_MODAL} button[type='submit']").click()
    page.locator(".dialog-overlay.visible").wait_for(state="visible")
    expect(page.locator(".dialog-overlay.visible")).to_contain_text("being created")


def test_awards_tab_and_gallery_anchor(alice):
    page, _ = alice
    slug = _seed_published("bob_test", "alice_test", "Gallery tile")
    page.goto(f"{BASE_URL}/profile/bob_test?tab=awards", wait_until="domcontentloaded")
    expect(page.locator(AWARDS_TAB)).to_be_visible()
    expect(page.locator(f"#award-{slug}")).to_be_visible()


def test_prominent_banner_visible(alice):
    page, _ = alice
    _seed_published("bob_test", "alice_test", "Prominent banner text")
    page.goto(f"{BASE_URL}/profile/bob_test", wait_until="domcontentloaded")
    expect(page.locator(".award-prominent")).to_be_visible()
    expect(page.locator(".award-prominent-desc")).to_contain_text("Prominent banner text")


def test_guest_can_read_awards_tab(browser):
    page = browser.new_page()
    try:
        slug = _seed_published("bob_test", "alice_test", "Guest gallery")
        page.goto(f"{BASE_URL}/profile/bob_test?tab=awards", wait_until="domcontentloaded")
        expect(page.locator(".awards-grid")).to_be_visible()
        expect(page.locator(f"#award-{slug}")).to_be_visible()
        expect(page.locator(GIVE_AWARD_BTN)).to_have_count(0)
    finally:
        page.close()


def test_avatar_badge_on_feed_when_prominent(alice):
    page, _ = alice
    _seed_published("bob_test", "alice_test", "Badge feed")
    # the Online now roster only lists active users, so make the awarded user active
    get_table("users").update(
        {
            "uid": get_table("users").find_one(username="bob_test")["uid"],
            "last_seen": datetime.now(timezone.utc).isoformat(),
        },
        ["uid"],
    )
    page.goto(f"{BASE_URL}/feed", wait_until="domcontentloaded")
    entry = page.locator(".online-user[title='bob_test']")
    expect(entry).to_be_visible()
    expect(entry.locator(AWARD_BADGE)).to_be_visible()