import json

from fasthtml.xtend import Script

from myfasthtml.core.commands import BaseCommand
from myfasthtml.core.instances import MultipleInstance


class Keyboard(MultipleInstance):
  def __init__(self, parent, _id=None, combinations=None):
    super().__init__(parent, _id=_id)
    self.combinations = combinations or {}
  
  def add(self, sequence: str, command: BaseCommand):
    self.combinations[sequence] = command
    return self
  
  def render(self):
    str_combinations = {sequence: command.get_htmx_params() for sequence, command in self.combinations.items()}
    return Script(f"add_keyboard_support('{self._parent.get_id()}', '{json.dumps(str_combinations)}')")
  
  def __ft__(self):
    return self.render()
