import pytest
from fasthtml.fastapp import fast_app

from myfasthtml.test.testclient import MyTestClient, TestableCheckbox


@pytest.fixture
def test_app():
  test_app, rt = fast_app(default_hdrs=False)
  return test_app


@pytest.fixture
def rt(test_app):
  return test_app.route


@pytest.fixture
def test_client(test_app):
  return MyTestClient(test_app)


@pytest.mark.parametrize("html,expected_value", [
    ('<input type="checkbox" name="male" checked />', True),
    ('<input type="checkbox" name="male" />', False),
])
def test_i_can_read_input(test_client, html, expected_value):
  input_elt = TestableCheckbox(test_client, html)
  
  assert input_elt.name == "male"
  assert input_elt.value == expected_value


def test_i_can_read_input_with_label(test_client):
  html = '''<label for="uid">Male</label><input id="uid" type="checkbox" name="male" checked />'''
  
  input_elt = TestableCheckbox(test_client, html)
  assert input_elt.fields_mapping == {"Male": "male"}
  assert input_elt.name == "male"
  assert input_elt.value == True


def test_i_can_check_checkbox(test_client, rt):
  html = '''<input type="checkbox" name="male" hx_post="/submit"/>'''
  
  @rt('/submit')
  def post(male: bool=None):
    return f"Checkbox received {male=}"
  
  input_elt = TestableCheckbox(test_client, html)
  
  input_elt.check()
  assert test_client.get_content() == "Checkbox received male=True"

  input_elt.uncheck()
  assert test_client.get_content() == "Checkbox received male=None"

  input_elt.toggle()
  assert test_client.get_content() == "Checkbox received male=True"
