# retoor <retoor@molodetz.nl>

import io
import requests
from datetime import datetime, timezone
from PIL import Image
from tests.conftest import BASE_URL
from devplacepy.attachments import store_attachment
from devplacepy.database import get_table
from devplacepy.utils import generate_uid, make_combined_slug

JSON = {"Accept": "application/json"}


def _png():
    buf = io.BytesIO()
    Image.new("RGBA", (16, 16), (90, 10, 10, 255)).save(buf, format="PNG")
    return buf.getvalue()


def _seed_published(receiver_username, giver_username, description):
    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()
    att = store_attachment(_png(), "award-256.png", receiver["uid"])
    get_table("awards").insert(
        {
            "uid": uid,
            "slug": slug,
            "description": description,
            "giver_uid": giver["uid"],
            "receiver_uid": receiver["uid"],
            "attachment_uid_512": att["uid"],
            "attachment_uid_256": att["uid"],
            "attachment_uid_64": att["uid"],
            "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_awards_tab_html_contains_grid_and_slug(seeded_db):
    slug = _seed_published("bob_test", "alice_test", "Tab award")
    r = requests.get(f"{BASE_URL}/profile/bob_test?tab=awards")
    assert r.status_code == 200
    assert "awards-grid" in r.text
    assert slug in r.text


def test_guest_can_read_awards_tab(seeded_db):
    _seed_published("bob_test", "alice_test", "Guest read")
    r = requests.get(f"{BASE_URL}/profile/bob_test?tab=awards")
    assert r.status_code == 200
    assert "Give Award" not in r.text


def test_awards_tab_json_includes_list(seeded_db):
    slug = _seed_published("bob_test", "alice_test", "JSON tab")
    r = requests.get(
        f"{BASE_URL}/profile/bob_test?tab=awards",
        headers=JSON,
    )
    assert r.status_code == 200
    data = r.json()
    assert data["awards_count"] >= 1
    assert any(item.get("slug") == slug for item in data.get("awards", []))


def test_awards_tab_absent_when_count_zero(seeded_db):
    bob = get_table("users").find_one(username="bob_test")
    get_table("users").update(
        {"uid": bob["uid"], "award_count": 0, "last_award_uid": None, "last_award_slug": None},
        ["uid"],
    )
    r = requests.get(f"{BASE_URL}/profile/bob_test")
    assert r.status_code == 200
    assert "tab=awards" not in r.text