from fasthtml.xtend import Script

from myfasthtml.controls.BaseCommands import BaseCommands
from myfasthtml.controls.helpers import Ids
from myfasthtml.core.commands import Command
from myfasthtml.core.instances import SingleInstance


class BoundariesState:
  def __init__(self):
    # persisted in DB
    self.width: int = 0
    self.height: int = 0


class Commands(BaseCommands):
  def update_boundaries(self):
    return Command(f"{self._prefix}UpdateBoundaries",
                   "Update component boundaries",
                   self._owner.update_boundaries).htmx(target=f"{self._owner.get_id()}")


class Boundaries(SingleInstance):
  """
  Ask the boundaries of the given control
  Keep the boundaries updated
  """
  
  def __init__(self, owner, container_id: str = None, on_resize=None, _id=None):
    super().__init__(owner, _id=_id)
    self._owner = owner
    self._container_id = container_id or owner.get_id()
    self._on_resize = on_resize
    self._commands = Commands(self)
    self._state = BoundariesState()
    self._get_boundaries_command = self._commands.update_boundaries()
  
  @property
  def width(self):
    return self._state.width
  
  @property
  def height(self):
    return self._state.height
  
  def update_boundaries(self, width: int, height: int):
    """
    Update the component boundaries.

    Args:
        width: Available width in pixels
        height: Available height in pixels
    """
    self._state.width = width
    self._state.height = height
    return self._on_resize() if self._on_resize else self._owner
  
  def render(self):
    return Script(f"initBoundaries('{self._container_id}', '{self._get_boundaries_command.url}');")
  
  def __ft__(self):
    return self.render()
