import pytest
from django.urls import reverse
from django.core.files.uploadedfile import SimpleUploadedFile

from aircox.models import Program


png_content = (
    b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde"
    + b"\x00\x00\x00\x0cIDATx\x9cc`\xf8\xcf\x00\x00\x02\x02\x01\x00{\t\x81x\x00\x00\x00\x00IEND\xaeB`\x82"
)


@pytest.mark.django_db()
def test_edit_program(user, client, program):
    client.force_login(user)
    response = client.get(reverse("program-detail", kwargs={"slug": program.slug}))
    assert response.status_code == 200
    assert b"fa-pen" not in response.content
    user.groups.add(program.editors)
    response = client.get(reverse("program-detail", kwargs={"slug": program.slug}))
    assert b"fa-pen" in response.content
    assert b"foobar" not in response.content
    response = client.post(reverse("program-edit", kwargs={"pk": program.pk}), {"content": "foobar"})
    response = client.get(reverse("program-detail", kwargs={"slug": program.slug}))
    assert b"foobar" in response.content


@pytest.mark.django_db()
def test_add_cover(user, client, program):
    assert program.cover is None
    user.groups.add(program.editors)
    client.force_login(user)
    cover = SimpleUploadedFile("cover1.png", png_content, content_type="image/png")
    r = client.post(
        reverse("program-edit", kwargs={"pk": program.pk}), {"content": "foobar", "new_cover": cover}, follow=True
    )
    assert r.status_code == 200
    p = Program.objects.get(pk=program.pk)
    assert "cover1.png" in p.cover.url
