from PySide6.QtWidgets import QGraphicsScene
from PySide6.QtCore import QRectF, QSize

from app.predictor import KeyboardPredictor
from app.ui.current_word import CurrentWordBox
from app.ui.keyboard import KeyboardLayout


WORD_BOX_HEIGHT_MODIFIER = 0.15
WORD_BOX_PADDING_ALL_SIDES = 10
WORD_BOX_MARGIN_BOTTOM = 20

class KeyboardScene(QGraphicsScene):
    def __init__(self):
        super().__init__()

        self.word_box = CurrentWordBox()
        self.addItem(self.word_box)

        self.predictor = KeyboardPredictor()

        self.keyboard = KeyboardLayout(self)
        self.keyboard.key_pressed_callback = self.on_key_clicked

    def layout_keys(self, view_size: QSize):
        view_width = view_size.width()
        view_height = view_size.height()

        word_box_height = view_height * WORD_BOX_HEIGHT_MODIFIER
        word_box_x = WORD_BOX_PADDING_ALL_SIDES
        word_box_y = WORD_BOX_PADDING_ALL_SIDES
        word_box_width = view_width - WORD_BOX_MARGIN_BOTTOM
        word_box_height_adjusted = word_box_height - WORD_BOX_MARGIN_BOTTOM

        self.word_box.set_geometry(
            word_box_x, word_box_y, word_box_width, word_box_height_adjusted
        )

        self.keyboard.layout_keys(view_size, top_offset=word_box_height)
        self.setSceneRect(QRectF(0, 0, view_width, view_height))

    def on_key_clicked(self, label: str):
        if label == "Space":
            self.word_box.clear()
            self.predictor.reset()
            self.keyboard.set_scale_factors({})
            return

        self.word_box.update_word(label)
        self.predictor.update(label)
        predictions = self.predictor.get_predictions()
        self.keyboard.set_scale_factors(predictions)
