import snowui
from pyglet.window import key
from gamelib.menu import Text
import rabbyt

class TextWidget(snowui.Widget):
    def __init__(self, on_submit, **args):
        snowui.Widget.__init__(self, bounds="rect", **args)
        self.text = Text("", font_size=12, rx=3, ry=3, color=(0,0,0,255))
        self.text.active = False
        self.add(self.text)
        self.on_submit = on_submit

    def do_focus(self):
        self.rgb = rabbyt.lerp(start=(1,1,1), end=(.7,.9,1), dt=1, extend="reverse")
        self.is_focused = True

    def do_blur(self):
        self.rgb = rabbyt.lerp(end=(1,1,1), dt=.3)
        self.is_focused = False

    def handle_text(self, text):
        self.text.text += text

    def on_key_press(self, symbol, modifiers):
        if not self.is_focused:
            return
        if symbol == key.BACKSPACE:
            self.text.text = self.text.text[:-1]
        elif symbol == key.ENTER:
            self.submit()

    def submit(self):
            self.on_submit(self.text.text)