# retoor <retoor@molodetz.nl>

from playwright.sync_api import expect
from tests.conftest import BASE_URL
from tests.e2e.post import create_post


def _post_comment(page, body):
    textarea = page.locator(".comment-form textarea[name='content']")
    textarea.fill(body)
    page.locator(".comment-form button:has-text('Post')").click()
    comment = page.locator(f".comment-text:has-text('{body}')")
    expect(comment).to_be_visible()
    return comment


def test_inline_edit_own_comment(alice):
    page, _ = alice
    create_post(page, "devlog", "Post for inline comment edit")
    comment = _post_comment(page, "Original comment body")
    edit_btn = page.locator(".comment-action-btn:has-text('Edit')").last
    expect(edit_btn).to_be_visible()
    edit_btn.click()
    edit_textarea = page.locator(".comment-edit-form textarea[name='content']")
    expect(edit_textarea).to_be_visible()
    expect(edit_textarea).to_have_value("Original comment body")
    edit_textarea.fill("Edited comment body")
    page.locator(".comment-edit-form button:has-text('Save')").click()
    expect(page.locator(".comment-text:has-text('Edited comment body')")).to_be_visible()
    expect(page.locator(".comment-text:has-text('Original comment body')")).to_have_count(0)


def test_cancel_inline_edit(alice):
    page, _ = alice
    create_post(page, "fun", "Post for cancel edit")
    _post_comment(page, "Keep this body")
    page.locator(".comment-action-btn:has-text('Edit')").last.click()
    edit_textarea = page.locator(".comment-edit-form textarea[name='content']")
    expect(edit_textarea).to_be_visible()
    edit_textarea.fill("Discarded body")
    page.locator(".comment-edit-form button:has-text('Cancel')").click()
    expect(page.locator(".comment-edit-form")).to_have_count(0)
    expect(page.locator(".comment-text:has-text('Keep this body')")).to_be_visible()


def test_non_owner_sees_no_edit_button(alice, bob):
    page, _ = alice
    create_post(page, "random", "Post owned by alice")
    _post_comment(page, "Alice only comment")
    post_url = page.url
    bob_page, _ = bob
    bob_page.goto(post_url, wait_until="domcontentloaded")
    expect(bob_page.locator(".comment-text:has-text('Alice only comment')")).to_be_visible()
    expect(bob_page.locator(".comment-action-btn:has-text('Edit')")).to_have_count(0)
