from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.graphics import Color, Ellipse
from kivy.clock import Clock
from kivy.core.window import Window

import random


class DrawWidget(Widget):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.point = None 
        self.x_pos = 0
        self.y_pos = 0
        self.moving = False

        Clock.schedule_interval(self.update, 1/60) # 1/60 = 60x za sekundu sa zavola procedura self.update

    def draw_point(self, x, y):
        self.canvas.clear()

        self.x_pos = x
        self.y_pos = y

        with self.canvas:
            Color(1, 0, 0)
            self.point = Ellipse(pos=(x, y), size=(10, 10))

    def start_moving(self):
        if self.point:
            self.moving = True

    def update(self, dt):
        if not self.moving or not self.point: 
            return  # pokial nie je zadany bod a hybanie, tak nic nerobime

        # random small step
        dx = random.uniform(-5, 5)
        dy = random.uniform(-5, 5)

        self.x_pos += dx
        self.y_pos += dy

        # update position
        self.point.pos = (self.x_pos, self.y_pos)


class MainLayout(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(orientation='vertical', **kwargs)

        self.draw_widget = DrawWidget()

        # zadavame text input
        self.input = TextInput(
            hint_text="Zadajte súradnice oddelené čiarkou",  # text, ktory sa zobrazi na zaciatku
            size_hint=(1, 0.1),
            multiline=False
        )

        # pridame dve tlacidla
        btn_draw = Button(text="Nakresli bod", size_hint=(1, 0.1))
        btn_move = Button(text="Začni pohyb", size_hint=(1, 0.1))

        btn_draw.bind(on_press=self.on_draw) # tuto pridavame callback
        btn_move.bind(on_press=self.on_move)

        self.add_widget(self.input)
        self.add_widget(btn_draw)
        self.add_widget(btn_move)
        self.add_widget(self.draw_widget)

        

    def on_draw(self, instance):
        text = self.input.text # nacitame text z textinputu

        try:
            x_str, y_str = text.split(",") # rozdelenie v desatinnej ciarke
            x = float(x_str.strip())
            y = float(y_str.strip())

            self.draw_widget.draw_point(x, y)

        except:
            print("Nesprávny vstup, zadajte súradnice vo formáte: x,y")

    def on_move(self, instance):
        self.draw_widget.start_moving()


class MyApp(App):
    def build(self):
        Window.clearcolor = (1, 1, 1, 1)

        return MainLayout()


if __name__ == "__main__":
    MyApp().run()