import pytest
from fasthtml.fastapp import fast_app

from myfasthtml.test.testclient import TestableInput, MyTestClient


@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)


def test_i_can_read_input(test_client):
  html = '''<input type="text" name="username" value="john_doe" />'''
  
  input_elt = TestableInput(test_client, html)
  
  assert input_elt.name == "username"
  assert input_elt.value == "john_doe"


def test_i_can_read_input_with_label(test_client):
  html = '''<label for="uid">Username</label><input id="uid" name="username" value="john_doe" />'''
  
  input_elt = TestableInput(test_client, html)
  assert input_elt.fields_mapping == {"Username": "username"}
  assert input_elt.name == "username"
  assert input_elt.value == "john_doe"


def test_i_can_send_values(test_client, rt):
  html = '''<input type="text" name="username" value="john_doe" hx_post="/submit"/>'''
  
  @rt('/submit')
  def post(username: str):
    return f"Input received {username=}"
  
  input_elt = TestableInput(test_client, html)
  input_elt.send("another name")
  
  assert test_client.get_content() == "Input received username='another name'"


def i_can_find_input_by_name(test_client):
  html = '''<label for="uid">Username</label><input id="uid" name="username" value="john_doe" />'''
  
  element = test_client.find_input("Username")
  assert False