# test that a change made in one browser window reaches another
# Derek Fujimoto
# Aug 2026

from fixtures import *
from playwright.sync_api import expect
import time

# the page polls /Shifts/Variables/stateid every 500 ms and redraws when it changes. that
# is the whole cross-browser sync mechanism and nothing exercised it
def test_sync_assignment_reaches_second_window(page, client, users_added):

    # a second window onto the same schedule
    other = page.context.new_page()
    other.set_default_timeout(5000)
    other.goto(f'{url}/?cmd=custom&page=ShiftSchedule')
    expect(by_id(other, 'cell_1_1')).to_be_attached()

    # both start empty
    assert by_id(other, 'summary_1_1').inner_text() == '', \
        f"Expected the second window's cell to start empty, got '{by_id(other, 'summary_1_1').inner_text()}'"

    # assign in the first window
    assign(page, 0, 1, 1)

    # the second window should pick it up from the poll, without being touched
    @try_again(timeout_s=10)
    def check():
        summary = by_id(other, 'summary_1_1').inner_text()
        assert summary == 'test0', \
            f"Expected the second window to show 'test0' at (row 1, col 1) after the first " \
            f"window assigned it, got '{summary}'"
    check()

    other.close()

# the same path for availability, which is written by a different rpc
def test_sync_availability_reaches_second_window(page, client, users_added):

    other = page.context.new_page()
    other.set_default_timeout(5000)
    other.goto(f'{url}/?cmd=custom&page=ShiftSchedule')
    expect(by_id(other, 'availcell_1_1')).to_be_attached()

    select_user(page, 'test0')
    click_and_drag(page, ((1,1),))

    @try_again(timeout_s=10)
    def check():
        count = by_id(other, 'availcell_1_1').inner_text()
        assert count == '1', \
            f"Expected the second window to show an availability count of 1 at (row 1, col 1) " \
            f"after the first window set it, got '{count}'"
    check()

    other.close()
