import pytest
from fasthtml.fastapp import fast_app

from myfasthtml.test.testclient import TestableSelect, 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_select(test_client):
  html = '''<select name="select_name">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  </select>
  '''
  select_elt = TestableSelect(test_client, html)
  assert select_elt.name == "select_name"
  assert select_elt.value == "option1"  # if no selected found, the first option is selected by default
  assert select_elt.options == [{'text': 'Option 1', 'value': 'option1'},
                                {'text': 'Option 2', 'value': 'option2'},
                                {'text': 'Option 3', 'value': 'option3'}]
  assert select_elt.select_fields == {'select_name': [{'text': 'Option 1', 'value': 'option1'},
                                                      {'text': 'Option 2', 'value': 'option2'},
                                                      {'text': 'Option 3', 'value': 'option3'}]}
  assert select_elt.is_multiple is False


def test_i_can_select_option(test_client):
  html = '''<select name="select_name">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  </select>
  '''
  select_elt = TestableSelect(test_client, html)
  select_elt.select("option2")
  assert select_elt.value == "option2"


def test_i_can_select_by_text(test_client):
  html = '''<select name="select_name">
  <option value="option1">Option 1</option>
  <option value="option2">Option 2</option>
  <option value="option3">Option 3</option>
  </select>
  '''
  select_elt = TestableSelect(test_client, html)
  select_elt.select_by_text("Option 3")
  assert select_elt.value == "option3"
