import json
from typing import TYPE_CHECKING

from textual.containers import Horizontal
from textual.message import Message
from textual.reactive import reactive
from textual.widget import Widget
from textual.widgets import Input, Label

from .messages import MessageFromRepl, MessageToRepl, PdbMessageType

if TYPE_CHECKING:
    from .pdbsharp import Pdbsharp


class DebugInputWidget(Input):
    BINDINGS = [
        ("ctrl+c", "interrupt", "Send Ctrl+C"),
    ]

    def action_interrupt(self):
        self.post_message(MessageToRepl(type=PdbMessageType.INT))
        self.value = ""

    def action_submit(self):
        self.post_message(
            MessageToRepl(type=PdbMessageType.COMMAND, content=self.value)
        )
        self.post_message(
            MessageFromRepl(json.dumps({"type": "pdbsharp", "message": self.value}))
        )
        self.value = ""


class DebugInputArea(Widget):
    app: Pdbsharp
    prompt: reactive[str] = reactive("", init=False)

    def watch_prompt(self, old, new) -> None:
        self.query_one(Label).update(new)

    def compose(self):
        with Horizontal():
            yield Label(self.prompt if self.prompt else "(-)")
            yield DebugInputWidget()
