import pytest
from fasthtml.fastapp import fast_app

from myfasthtml.controls.button import mk_button
from myfasthtml.core.commands import Command, CommandsManager
from myfasthtml.core.testclient import MyTestClient, TestableElement


def new_value(value):
  return value


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


@pytest.fixture()
def rt(user):
  return user.app.route


def test_i_can_trigger_a_command(user):
  command = Command('test', 'TestingCommand', new_value, "this is my new value")
  testable = TestableElement(user, mk_button('button', command))
  testable.click()
  assert user.get_content() == "this is my new value"


def test_error_is_raised_when_command_is_not_found(user):
  command = Command('test', 'TestingCommand', new_value, "this is my new value")
  CommandsManager.reset()
  testable = TestableElement(user, mk_button('button', command))
  
  with pytest.raises(ValueError) as exc_info:
    testable.click()
  
  assert "not found." in str(exc_info.value)


def test_i_can_play_a_complex_scenario(user, rt):
  command = Command('test', 'TestingCommand', new_value, "this is my new value")
  
  @rt('/')
  def get(): return mk_button('button', command)
  
  user.open("/")
  user.should_see("button")
  
  user.find_element("button").click()
  user.should_see("this is my new value")
