from kivy.app import App
from kivy.core.window import Window
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.core.text import Label as CoreLabel
from kivy.graphics import Color, Ellipse, Rectangle
from kivy.lang import Builder
from kivy.properties import ObjectProperty, NumericProperty, BooleanProperty, StringProperty

from light import CUR_LIGHT, LIGHTS, LightColor

from numpy import isnan

gx = 0
gy = 0

class ConfigPoint:
    def __init__(self, id, x, y):
        self.id = id
        self.x = x
        self.y = y
        self.el = None
        self.txt = None

POINTS = []

class LightTarget:
    def __init__(self):
        self.x = 0.5
        self.y = 0.5
        self.ellipse = None
        self.diameter = 40.



class MyImage(Image):
    def __init__(self, **kwargs):
        super(MyImage, self).__init__(**kwargs)    

        self.light_dots = []
        pass

    def on_kv_post(self, touch):
        with self.canvas:
            i = 0
            for p in POINTS:
                Color(1,1,0)
                d = 10
                pos = (p.x*self.size[0]-d/2, p.y*self.size[1]-d/2)
                el = Ellipse(pos=pos, size=(d,d))
                p.el = el
                
                mylabel = CoreLabel(text=str(p.id), font_size=25, color=(1,0,0,1))
                # Force refresh to compute things and generate the texture
                mylabel.refresh()
                # Get the texture and the texture size
                texture = mylabel.texture
                texture_size = list(texture.size)
                txt = Rectangle(texture=texture, size=texture_size, pos=pos)
                p.txt = txt
                
                i += 1
                
            # init spotlight focus dot
            col = [(1,0,1), (0,0,1)]
            for i in range(2):
                Color(*col[i])
                l = LightTarget()
                l.y = 0.5
                l.x = 0.4 + 0.2 * i
                l.ellipse = Ellipse(pos=self.normalised_to_pos(l.x, l.y, l.diameter), size=(l.diameter, l.diameter))
                self.light_dots.append(l)





    def normalised_to_pos(self, x, y, d):
        pos = (x*self.size[0]-d/2, y*self.size[1]-d/2)
        pos_wnd = self.to_parent(pos[0], pos[1], True)

        return pos_wnd

    def on_size(self,  *args):
        # Calculate new position of interpolation base points to display on the stage
        for p in POINTS:
            d = 10.

            pos_wnd = self.normalised_to_pos(p.x, p.y, d)

            p.el.pos = pos_wnd
            p.txt.pos = (pos_wnd[0], pos_wnd[1]+d)

        for l in self.light_dots:
            l.ellipse.pos = self.normalised_to_pos(l.x, l.y, l.diameter)
            
            
    def set_light(self, pos):
        if not self.collide_point(*pos): return
        
        orig = pos
        mn = self.pos
        mx = (mn[0] + self.size[0], mn[1] + self.size[1])

        print(CUR_LIGHT)

        for i in CUR_LIGHT:
            pos = orig
            l = self.light_dots[i]

            l.ellipse.pos = (pos[0]-l.diameter/2, pos[1] -l.diameter/2)

            pos = self.to_local(orig[0], orig[1], True)
            normalised = (pos[0] / self.size[0], pos[1] / self.size[1])

            l.x = normalised[0]
            l.y = normalised[1]

            pt = LIGHTS[i].interp(normalised)

            print(f'{normalised[0]:.3f} {normalised[1]:.3f}')

            global gx, gy
            gx = normalised[0]
            gy = normalised[1]

            if not isnan(pt[0]):
                pt = [round(n) for n in pt]
                #print(pt)
                LIGHTS[i].pan = pt[0]
                LIGHTS[i].tilt = pt[1]

            
    def on_touch_down(self, touch):
        self.set_light(touch.pos)
        
    def on_touch_move(self, touch):
        self.set_light(touch.pos)

class Controls(BoxLayout):
    light = ObjectProperty(LIGHTS[0], rebind=True)
    light_id = StringProperty("0")
    pass
 
 
class Controller(BoxLayout):
    cur_light_id = NumericProperty(0)
    light = ObjectProperty(LIGHTS[0], rebind=True)
    
    def __init__(self, **kwargs):
        super(Controller, self).__init__(**kwargs)
        self._keyboard = Window.request_keyboard(self._keyboard_closed, self)
        self._keyboard.bind(on_key_down=self._on_key_down)

    def _on_key_down(self, keyboard, keycode, text, modifiers):
        #print(keycode)
        if keycode[1] == 'up':
            LIGHTS[1].tilt += 1
        elif keycode[1] == 'down':
            LIGHTS[1].tilt -= 1
        elif keycode[1] == 'left':
            LIGHTS[1].pan += 1
        elif keycode[1] == 'right':
            LIGHTS[1].pan -= 1

        if keycode[1] == 'w':
            LIGHTS[0].tilt += 1
        elif keycode[1] == 's':
            LIGHTS[0].tilt -= 1
        elif keycode[1] == 'a':
            LIGHTS[0].pan += 1
        elif keycode[1] == 'd':
            LIGHTS[0].pan -= 1

        print(f'{gx:.3f},{gy:.3f},{LIGHTS[0].tilt},{LIGHTS[0].pan},{LIGHTS[1].tilt},{LIGHTS[1].pan}')

    def _keyboard_closed(self):
        pass

    def set_light(self, light):
        global CUR_LIGHT

        if light == 'left':
            CUR_LIGHT = [0]
        elif light == 'right':
            CUR_LIGHT = [1]
        elif light == 'both':
            CUR_LIGHT = [0, 1]
        
        print('Set done')
        
        

class LightApp(App):
    def build(self):
        return Controller()
    #    # c.add_widget(StageWidget())
    #     return c

    def on_stop(self):
        pass
        # print("Stopped")
        #
        # for l in LIGHTS:
        #     l.tilt = 0
        #     l.pan = 0
        #     l.color = 0
        #     l.focus = 0
        #     l.dimmer = 0
        #     l.close_shutter()


    pass