#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pygame, math, time, serial, random, datetime,os
global arrayled, arrayled_default, pathname, text, COM_PORT



init_values = open('config.txt')
for init_value in init_values: 
    var = init_value.rstrip()
    for char in range(len(var)):
        if init_value[char] == ' ':
            if init_value[:char] == "text":
                text = init_value[char+3:-1]
            elif init_value[:char] == "pathname":
                pathname = init_value[char+3:-1]
            elif init_value[:char] == "animation":
                animation = init_value[char+3:-1]
            elif init_value[:char] == "COM_PORT":
                COM_PORT = init_value[char+3:-1]
            elif init_value[:char] == "Baudrate":
                Baudrate = init_value[char+3:-1]
            elif init_value[:char] == "screen_width":
                screen_width = init_value[char+3:]


dict_circles = {}
images_first_screen_dict = {}
images_second_screen_dict = {}
print('COM_PORT: ' + COM_PORT)
pygame.init()
pygame.display.set_caption('LED_Font8x12')
width = int(screen_width)
height = 6/11 * width
size = width, int(height)
screen = pygame.display.set_mode((size) , pygame.HWSURFACE | pygame.DOUBLEBUF)
if str(COM_PORT) == "None":
    pass
else: 
    ser = serial.Serial()
    ser.baudrate = int(Baudrate)
    ser.port = str(COM_PORT)
    ser.timeout = 0.0001
    ser.open()
    time.sleep(5)
    print('Connected to COM_PORT: ' + COM_PORT)


rot = (255,0,0)
gruen = (0,255,0)
blau = (0,0,255)
gelb = (255,255,0)
tuerkis = (0,255,255)
lila = (255,0,255)
weiss_rahmen = (255,255,255)
weiss =(255,255,255)
schwarz = (0,0,0)
circles_color= [schwarz, rot, gruen, blau, gelb, tuerkis, lila, weiss]

offset_x=int((9/11)*width)
offset_y=int((1/6)*height)        
width_x = int((39/275)*width)
width_y= int((21/200)*height)

radius = height*0.05
rad_circles = int((3/110)*width)
drag = False 
color_chosen = schwarz
pathname = pathname
time_value = 0.59
drag = False
animation = str(animation)
text = str(text)




data =     [("c00","c01","c02","c03","c04","c05","c06","c07","c08","c09","c010","c011"), \
            ("c10","c11","c12","c13","c14","c15","c16","c17","c18","c19","c110","c111"), \
            ("c20","c21","c22","c23","c24","c25","c26","c27","c28","c29","c210","c211"), \
            ("c30","c31","c32","c33","c34","c35","c36","c37","c38","c39","c310","c311"), \
            ("c40","c41","c42","c43","c44","c45","c46","c47","c48","c49","c410","c411"), \
            ("c50","c51","c52","c53","c54","c55","c56","c57","c58","c59","c510","c511"), \
            ("c60","c61","c62","c63","c64","c65","c66","c67","c68","c69","c610","c611"), \
            ("c70","c71","c72","c73","c74","c75","c76","c77","c78","c79","c710","c711")]


arrayled = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
            [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
            [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
            [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],  
            [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
            [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
            [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
            [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]

arrayled_default = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],  
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                    [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]


hexarray = [] 



images_first_screen = ["start_schrift", "start_animation", "Stop", "zeit_intervall", "neue_animation", "animationswahl"]
images_second_screen = ["bild_speichern", "animation_speichern", "exit"]

images_first_screen_functions = ['text_show', 'animation_show', 'stop', 'time_set', 'animation_new', 'animation_chose']
images_second_screen_functions = ['picture_save', 'animation_save', 'exit_second_screen']
screen_choose = {'mode1': 'images_first_screen', 'mode2': 'images_second_screen'}



class LedFont(object):
          
    def __init__(self, color, pos, rad, width,  count): 
        self.color = color
        self.pos = pos
        self.rad = rad
        self.width = width
        self.count = count
    

    def get_circle_pos(a,b):
        pos_x = int((3/55)*width) + (b * int((7/110)* width))
        pos_y = int((3/55)*width) + (a *int((7/110)* width))
        return pos_y, pos_x
      

    def init_circles():   
        for a in range(0,8,1):
            for b in range(0,12,1):
                dict_circles[data[a][b]] = LedFont(weiss_rahmen, (LedFont.get_circle_pos(a,b)[1],LedFont.get_circle_pos(a,b)[0]), int((3/110) * width), 1, 0)
    
    def change_value(arrayled):
        for a in range(0,8,1):          
            for b in range(0,12,1):
                if arrayled[a][b] == 0:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = schwarz                 
                if arrayled[a][b] == 1:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = rot
                if arrayled[a][b] == 2:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = gruen
                if arrayled[a][b] == 3:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = blau
                if arrayled[a][b] == 4:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = gelb
                if arrayled[a][b] == 5:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = tuerkis
                if arrayled[a][b] == 6:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = lila
                if arrayled[a][b] == 7:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = weiss
                if arrayled[a][b] == 0:
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    dict_circles.get(("c" + str(a) + str(b))).color = schwarz                    

    def draw_circles(screen):
        for a in range(0,8,1):
            for b in range(0,12,1):
                pygame.draw.circle(screen,dict_circles.get(("c" + str(a) + str(b))).color,\
                                          dict_circles.get(("c" + str(a) + str(b))).pos, \
                                          dict_circles.get(("c" + str(a) + str(b))).rad,\
                                          dict_circles.get(("c" + str(a) + str(b))).width)
     

    def remove_circles(screen):
        for a in range(0,8,1):
            for b in range(0,12,1):             
                dict_circles.get(("c" + str(a) + str(b))).color = (0,0,0) 
                dict_circles.get(("c" + str(a) + str(b))).width = 0
                pygame.draw.circle(screen,dict_circles.get(("c" + str(a) + str(b))).color,\
                                          dict_circles.get(("c" + str(a) + str(b))).pos, \
                                          dict_circles.get(("c" + str(a) + str(b))).rad,\
                                          dict_circles.get(("c" + str(a) + str(b))).width)
     
    def mouse_click_in_circle(mouse, color_chosen):
        for a in range(0,8,1):
            for b in range(0,12,1):
                if (math.sqrt(((mouse[0]- (LedFont.get_circle_pos(a,b)[1]))**2) + ((mouse[1] - LedFont.get_circle_pos(a,b)[0]))**2)) <= math.sqrt(int((3/110)*width)**2):  #Kreisformel: (x-m)^2+(y-m)^2 <= r^2 --> im kreis
                    
                    dict_circles.get(("c" + str(a) + str(b))).width = 0
                    if color_chosen == schwarz: 
                        dict_circles.get(("c" + str(a) + str(b))).color = schwarz
                        arrayled[a][b] = 0
                    elif color_chosen == rot: 
                        dict_circles.get(("c" + str(a) + str(b))).color = rot
                        arrayled[a][b] = 1                        
                    elif color_chosen == gruen: 
                        dict_circles.get(("c" + str(a) + str(b))).color = gruen
                        arrayled[a][b] = 2                                           
                    elif color_chosen == blau: 
                        dict_circles.get(("c" + str(a) + str(b))).color = blau
                        arrayled[a][b] = 3
                    elif color_chosen == gelb: 
                        dict_circles.get(("c" + str(a) + str(b))).color = gelb
                        arrayled[a][b] = 4
                    elif color_chosen == tuerkis: 
                        dict_circles.get(("c" + str(a) + str(b))).color = tuerkis
                        arrayled[a][b] = 5
                    elif color_chosen == lila: 
                        dict_circles.get(("c" + str(a) + str(b))).color = lila
                        arrayled[a][b] = 6
                    elif color_chosen == weiss: 
                        dict_circles.get(("c" + str(a) + str(b))).color = weiss
                        arrayled[a][b] = 7
                    
            
                   
                    
                   
                        
def serial_write(arrayled):
    for rows in range(0,8,1):
        send_data = bytes(arrayled[rows][0:12])
        ser.write(send_data)
                

    

#str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute) + " "   

def change_text():
    return str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute) + " "    
                
def LedFont_to_binary(arrayled):
    row_string_bin = ""
    binary_string_list = []
    for a in range(0,8,1):
        for b in range(0,12,1):
            if arrayled[a][b] == 0:
                row_string_bin= row_string_bin +"000"
            elif arrayled[a][b] == 1:
                row_string_bin= row_string_bin +"001"
            elif arrayled[a][b] == 2:
                row_string_bin= row_string_bin +"010"
            elif arrayled[a][b] == 3:
                row_string_bin= row_string_bin +"011"
            elif arrayled[a][b] == 4:
                row_string_bin= row_string_bin +"100"
            elif arrayled[a][b] == 5:
                row_string_bin= row_string_bin +"101"
            elif arrayled[a][b] == 6:
                row_string_bin= row_string_bin +"110"
            elif arrayled[a][b] == 7:
                row_string_bin= row_string_bin +"111"
            
        binary_string_list.append(row_string_bin)
        row_string_bin =""
    
    return binary_string_list
                
   
                
def binary_to_hex(binary_string_list):
    hex_string_list = []
    for binary in binary_string_list:
        binary_string = str(binary)
        hex_string= hex(int(binary_string, 2))
        hex_string_list.append(hex_string)
   
    return hex_string_list
    
def hex_to_binary(arrayled, hex_data):          # Hex to Bin Converter Funktion. Aufpassen: die Funktion dreht die Hex Bitfolge um 90° !! 
    for a in range(0,8,1):  
        intVal = int(hex_data[a], 16)
        binVal = bin(intVal)[2:].zfill(36)
        b = 0    
        for value in range(0,36,3):
            sel_bin_val = binVal[value:value+3]
            arrayled[a][b]= int(sel_bin_val, 2)
            b = b+ 1
   
    return arrayled
    

        
def stop(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    global COM_PORT
    arrayled_default = [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],  
                        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], 
                        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]]    

    screen.fill(schwarz)
    if mode == 'mode1':
        for button in images_first_screen_dict:
            screen.blit(images_first_screen_dict.get(button).image, images_first_screen_dict.get(button).position)
            
        
    elif mode == 'mode2':
        for button in images_second_screen_dict:
            screen.blit(images_second_screen_dict.get(button).image, images_second_screen_dict.get(button).position)    
    
    pygame.display.update()
    if str(COM_PORT) == "None":
        pass
    else:
        serial_write(arrayled_default)
    LedFont.init_circles()
    images_first_screen_dict.get('Stop').state = False
    return arrayled_default, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
    

def test_bin(arrayled):
    binary_string_list = LedFont_to_binary(arrayled)
    hex_string_list=binary_to_hex(binary_string_list)
    return hex_string_list
    
      
def check_filenames():
    global pathname
    for datei in range(len(os.listdir(pathname))+1):
        if os.path.isfile(pathname+'animation' + str(datei)+'.txt') == False:
            return 'animation'+str(datei) +'.txt'
    
    
def check_filenames_new():
    global pathname
    for datei in range(len(os.listdir(pathname))):
        if os.path.isfile(pathname +'neueanimation.txt') == True:
            return True
    return False



def animation_save(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    global data_hex_out, pathname
    all_good = check_filenames_new()
    if all_good == False:
        print('Fehler')
        pass
    
    elif all_good == True:    
        new_name = check_filenames()
        os.rename(pathname + animation, pathname + new_name)
        images_second_screen_dict.get('animation_speichern').state = False
        animation = new_name
        print('Animation gespeichert: ' + pathname + animation)
        print('Zum Fortfahren auf Fertig klicken')
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
    

def picture_save(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    global pathname, data_hex_out
    animation = 'neueanimation.txt'
    available = check_filenames_new()
    if available == False:
        data_hex_out = open(pathname + animation, "w")
    elif available == True:
        data_hex_out = open(pathname+ animation, "a")
    
    hex_string_list = test_bin(arrayled)
    for hex_val in hex_string_list:
        hex_val_formated = str(hex_val) + ", "
        data_hex_out.write(hex_val_formated)
    
    data_hex_out.write("\n")
    data_hex_out.close()
    images_second_screen_dict.get('bild_speichern').state = False
    pygame.draw.rect(screen, schwarz, (offset_x, 0*offset_y+ int((2/60)*height), width_x, width_y), 3)
    print('Bild gespeichert in: ' + pathname + animation)
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
       
def get_hex_data(line, animation):  
    global pathname
    data_hex_in = open(pathname+animation, "r").readlines()           
    outline = []
    splited_data = data_hex_in[line].split()
    for line in range(len(splited_data)):
        cuttedstring = splited_data[line][2:-1]         
        outline.append(cuttedstring[:]) 
    return outline    
    
def animation_show(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    
    global arrayled_default, pathname,COM_PORT
    
    lines = open(pathname+animation, "r").readlines() 
    LedFont.init_circles()                                             
    for line in range(len(lines)):
        arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation=handle_events(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
        if images_first_screen_dict.get('start_animation').state == False:
            arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation = stop(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
            return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
        else:        
            hex_data = get_hex_data(line, animation)
            print(hex_data)
            arrayled = hex_to_binary(arrayled, hex_data) 
            LedFont.change_value(arrayled)
            time.sleep(time_value)
            if str(COM_PORT) == "None":
                pass
            else:
                serial_write(arrayled)
            LedFont.draw_circles(screen)
            pygame.display.update()
   
    
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
      
    
def animation_new(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    global COM_PORT
    colors.load_circles()
    pygame.draw.circle(screen, weiss_rahmen, ((int((9/11)* width)+rad_circles,int((1/2)* height)+ rad_circles)), (int((3/110) * width)), 1)
 
    pygame.display.update()        
    if mouse_clicked != None:
        color_chosen = colors.color_chose(mouse_clicked, color_chosen)
        mouse = (0,0)
        if 0 < mouse_clicked[0]< int((9/11)*width) or drag == True:   
            drag = True
            LedFont.mouse_click_in_circle(mouse, color_chosen)
            LedFont.draw_circles(screen)
            if str(COM_PORT) == "None":
                pass
            else:
                serial_write(arrayled)
            pygame.display.update()            
    else: 
        LedFont.mouse_click_in_circle(mouse, color_chosen)
        LedFont.draw_circles(screen)
        if str(COM_PORT) == "None":
            pass
        else:
            serial_write(arrayled)
        pygame.display.update()
        screen.fill(schwarz, (int((9/11)*width)-10, int((1/2)*height)-10, int((2/11)*width), int((1/2)*height)))
    
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation


def change_text():
    return str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute) + " "      

def get_hexvalues(digit):                                                          # Funktion zum einlesen der hex-Werte aus Datei: "font_header2txt", ließt HexWerte als String variablen aus(1Hex Wert beschreibt eine 7 Bits
    fin = open("font_header2.txt", "r").readlines()
    outline = []
    for line in fin:
        line_new = line.split()    
        if line_new[5] == digit:
            for string_val in range(0,5,1): 
                now_line = line_new[string_val]
                cuttedstring = now_line[2:-1]         
                outline.append(cuttedstring[:])
    if len(outline) == 0:
        outline = ['00', '00', '00', '00', '00']
        return outline
    else:
        return outline


def shift_right(rows, arrayled):
    
    shifted_array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    shifted_array[1:] = arrayled[rows][:-1]
    return shifted_array

def shift_left(rows, arrayled):

    shifted_array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
    shifted_array[:-1] = arrayled[rows][1:]
    return shifted_array


def change_text():
    return str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute) + " "


def hex_to_bin(hexarray, arrayled):                                                          # Hex to Bin Converter Funktion. Aufpassen: die Funktion dreht die Hex Bitfolge um 90° !! 
    for a in range(0,5,1):
        intVal = int(hexarray[a], 16)
        binVal = bin(intVal)[2:].zfill(7)
        for b in range(0,7,1):
            arrayled[7-b][a+12] = int(binVal[b])
    return arrayled



def different_colors(arrayled):                                                    # Funktion für zufällige Farben der Zeichen
    color = random.randrange(1,8,1)
    for a in range(0,5,1):
        for b in range(0,7,1):
            if arrayled[7-b][a+12] == 1:
                arrayled[7-b][a+12] = color
    return arrayled


def change_text():
    return str(datetime.datetime.now().hour) + ":" + str(datetime.datetime.now().minute) + " "

def show_text(text1, arrayled):
    for digit in text1:                                                         # ---------> 1. For Schleife iteriert über jedes Zeichen(Buchstabe, Nummer, Sonderzeichen) in String variable "text" 
        hexarray = get_hexvalues(digit)                                         # Einlesen der Hex-Werte aus font_header2.txt, dort sind die LED Darstellungen für die Ziffern (A-Z), (0-9) und Sonderzeichen in Hex-Form gespeichert
        arrayled = hex_to_bin(hexarray, arrayled)                               # Konvertieren der hex-Werte aus "hexarray" in binäre Werte in liste "arrayled"
        arrayled = different_colors(arrayled)                                   # optional: zufällige Farbe für die Zeichen, bei Weglassen nur Rote LEDs
        return arrayled                                                         # ---------> 2. For Schleife setzt das Zeichen in Klasse LedFont ein und die Zeichen werden auf dem Bildschirm mit pygame angezeigt.              
                                                                                # Neu anlegen/Rückstellen für jede Circle Klasse (siehe LedFont)  
                                                                                # Werte aus "arrayled" auslesen; Werte stehen für neue Farbattribute der Circle Klassen
                                                                                # Werte aus "arrayled" seriell auf Arduino übertragen
                                                                                # Circles nach self.Attributen (siehe Klasse Led_Font) zeichnen
                                                                                # Ausgabe auf Display
                                                                                # Pause
                                                                                # --------> 3. For Schleife schiebt in jeder Zeile (range(0,8,1) --> 8 Zeilen) die Liste nach links, das passiert siehe 2. for Schleife(range(0,7,1) -->7x, dann wird das nächste Zeichen eingelesen usw...da die Ziffern immer 5 Spalten haben, bleiben 2 Spalten als "Leerzeichen" zwischen den Buchstaben/Zeichen
                                                                                # Zeichen wird nach links geschoben (siehe Beispiel Buchstabe A in "arrayled")                    
            
                                                                                #  1  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] 
                                                                                #  2  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,0,0]
                                                                                #  3  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]
                                                                                #  4  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]
                                                                                #  5  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1]  --->  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0]  --->  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]
                                                                                #  6  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0]
                                                                                #  7  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]
                                                                                #  8  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0]        [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,0]





def text_show(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    global text
    if text =='Uhrzeit':
        text1 = change_text()
    else:
        text1 = text 
    for digit in range(len(text1)):
        arrayled = show_text(text1[digit], arrayled)
        for digit in range(0,7,1):
            LedFont.init_circles()
            LedFont.change_value(arrayled)
            time.sleep(time_value)
            if str(COM_PORT) == "None":
                pass
            else:
                serial_write(arrayled)
            LedFont.draw_circles(screen)
            pygame.display.update() 
            for shiftings in range(0,8,1):
                arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation=handle_events(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
                if images_first_screen_dict.get('start_schrift').state == False:
                    arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation = stop(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
                    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
                else:
                    arrayled[shiftings]= shift_left(shiftings, arrayled)
            LedFont.remove_circles(screen)
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation


def exit_second_screen(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation = stop(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
    images_second_screen_dict.get('exit').state = False
    images_first_screen_dict.get('neue_animation').state = False
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation

def time_set(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    
    
    slider_background = pygame.draw.rect(screen, (100,100,100), (int(width*(9/11)) * 0.25-radius,  height * 0.45, int(width*(9/11)) *0.5+ 2* radius,   height*0.1))    #Rectangle zwischen 1/4 width und 3/4 width
    if slider_value == None:
        slider = pygame.draw.circle(screen, (255,255,0), (int(width*(9/11)/2),int(height/2)), int(height*0.05), 0)
    else:
        slider = pygame.draw.circle(slider_value[0], slider_value[1], slider_value[2], slider_value[3])
    
    myfont_time = pygame.font.SysFont('comicsansms', int((3/110)*width))
    textsurface_time = myfont_time.render(str(round(time_value,2)) +' s', False, (255, 255, 255))
    screen.blit(textsurface_time, (int((8/22)* width), int((12/20)* height)))
    pygame.display.flip()

    if mouse_clicked == None:
        pass
    
    elif (math.sqrt(((mouse_clicked[0]-(slider[0]+(int(height*0.05))))**2) + ((mouse_clicked[1] - (slider[1]+int(height*0.05))))**2) <= math.sqrt(int(height*0.05)**2)):
        drag = True
        
    screen.fill(schwarz, (int((8/22)* width), int((12/20)* height), int((4/11)*width), int((1/15)* height)))
    slider_background = pygame.draw.rect(screen, (100,100,100), (int(width*(9/11)) * 0.25-radius,  height * 0.45, int(width*(9/11)) *0.5+ 2* radius,   height*0.1))
    
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation


def animation_chose(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
    
    global pathname
   
    offset_x_chose = int((1/55)* width)
    offset_y_chose = int((1/55)* width)      
    width_x_chose = len(text[:-4])* int((14/1000)* width)
    width_y_chose = int((9/220)*width)
          
    for datei in range(len(os.listdir(pathname))):
        myfont = pygame.font.SysFont("comicsansms", int((3/110)*width))
        textsurface = myfont.render(os.listdir(pathname)[datei][:-4], False, (255, 255, 255))
        rect = pygame.draw.rect(screen, (100,100,0), (offset_x_chose, offset_y_chose, len(os.listdir(pathname)[datei][:-4])* int((15/1000)* width),width_y_chose))
        screen.blit(textsurface, (offset_x_chose, offset_y_chose))
        offset_x_chose =offset_x_chose + (len(os.listdir(pathname)[datei][:-4])* int((15/1000)* width)) + int((1/55)* width)
        if offset_x_chose > int((7/11)* width):
            offset_x_chose = int((1/55)* width)
            offset_y_chose = offset_y_chose + width_y_chose + int((1/55)* width)
        
        
    pygame.display.update()       
    offset_x_chose = int((1/55)* width)
    offset_y_chose = int((1/55)* width)    
    if mouse_clicked != None:
        for datei in range(len(os.listdir(pathname))):
            if offset_x_chose + (len(os.listdir(pathname)[datei][:-4])* int((14/1000)* width)) >mouse_clicked[0] > offset_x_chose and offset_y_chose + width_y_chose > mouse_clicked[1]> offset_y_chose:
                animation = os.listdir(pathname)[datei]         
                pygame.draw.rect(screen, weiss_rahmen, (offset_x_chose, offset_y_chose, (len(os.listdir(pathname)[datei][:-4])* int((15/1000)* width)), width_y_chose), 3)
                print('Animation: ' + pathname + animation + ' ausgewählt')
            offset_x_chose = offset_x_chose + (len(os.listdir(pathname)[datei][:-4])* int((15/1000)* width)) + int((1/55)* width)
            if offset_x_chose > int((7/11)* width):
                offset_x_chose = int((1/55)* width)
                offset_y_chose = offset_y_chose + width_y_chose + int((1/55)* width) 
    
    else:
        pass
    pygame.draw.rect(screen, weiss, (offset_x, 5*offset_y+ int((2/60)*height), width_x, width_y), 2)
    pygame.display.update()            
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
    

class colors(object):
    
    def __init__(self, circle, position, color):
        self.circle = circle
        self.position = position
        self.color = color
         
        
    def get_pos(circle):
        
        if circle == 0:
            x = int((9/11)* width)+rad_circles
            y = int((1/2)* height)+ rad_circles 
        if circle == 1:
            x= int((9/11)* width) + int((7/110)* width)+rad_circles
            y = int((1/2)* height) +rad_circles
        if circle == 2:
            x= int((9/11)* width)+rad_circles
            y = int((1/2)* height) + int((7/110)* width)*1 +rad_circles
        if circle == 3:
            x= int((9/11)* width)  + int((7/110)* width)+rad_circles
            y = int((1/2)* height) + int((7/110)* width)*1 +rad_circles
        if circle == 4:
            x= int((9/11)* width) +rad_circles
            y = int((1/2)* height) +int((7/110)* width)*2 +rad_circles
        if circle == 5:
            x= int((9/11)* width) + int((7/110)* width)+rad_circles
            y = int((1/2)* height) + int((7/110)* width)*2 +rad_circles
        if circle == 6:
            x= int((9/11)* width) +rad_circles
            y = int((1/2)* height) + int((7/110)* width)*3 +rad_circles
        if circle == 7:
            x= int((9/11)* width) + int((7/110)* width)+rad_circles
            y = int((1/2)* height) + int((7/110)* width)*3  +rad_circles      
            
        return x,y
    
        
    def load_circles():
        for circle in range(len(circles_color)):
            pygame.draw.circle(screen,circles_color[circle], (colors.get_pos(circle)[0],colors.get_pos(circle)[1]), (int((3/110) * width)), 0) 
        
    def color_chose(mouse, color_chosen):
        for circle in range(len(circles_color)):
            if (math.sqrt(((mouse[0]- (colors.get_pos(circle)[0]))**2) + ((mouse[1] - colors.get_pos(circle)[1]))**2)) <= math.sqrt(int((3/110)*width)**2):
                color_chosen = circles_color[circle]
                pygame.draw.circle(screen, weiss_rahmen, (colors.get_pos(circle)[0],colors.get_pos(circle)[1]), (int((4/110) * width)), 1) 
                #pygame.display.update()
        return color_chosen
          
                           
class buttons(object):
    
    def __init__(self, image, position, state, function):
        self.image = image 
        self.position = position
        self.state = state
        self.function = function
        
        
    def load_images(mode):
        for button in range(len(images_first_screen)):
            image = pygame.image.load(images_first_screen[button] + ".bmp").convert_alpha()
            image = pygame.transform.scale(image, (width_x, width_y))
            position = image.get_rect(x=offset_x, y=button*offset_y+int((2/60)*height), w= width_x, h=width_y)
            state = False
            function = images_first_screen_functions[button]
            images_first_screen_dict[images_first_screen[button]] = buttons(image, position, state, function)
       
        
        for button in range(len(images_second_screen)):
            image = pygame.image.load(images_second_screen[button] + ".bmp").convert_alpha()
            image = pygame.transform.scale(image, (width_x, width_y))
            position = image.get_rect(x=offset_x, y=button*offset_y+int((2/60)*height), w= width_x, h=width_y)
            state = False
            function = images_second_screen_functions[button]
            images_second_screen_dict[images_second_screen[button]] = buttons(image, position, state, function) 
        return mode 
       
  
    def check_state(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
        for statement in range(len(images_first_screen)):
            if images_first_screen_dict[images_first_screen[statement]].state == True:
                arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation = eval(images_first_screen_dict[images_first_screen[statement]].function)(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
                   
                           
        for statement in range(len(images_second_screen)):
            if images_second_screen_dict[images_second_screen[statement]].state == True:
                arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation = eval(images_second_screen_dict[images_second_screen[statement]].function)(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
                    
        return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
                
                                   


def handle_events(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation):
      
    for event in pygame.event.get():
        
        if event.type ==pygame.QUIT:
            
            pygame.quit()
            quit()            
        if event.type == pygame.MOUSEBUTTONDOWN:
            mouse_clicked=pygame.mouse.get_pos()
            if mode == 'mode1':
                arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation=stop(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
                arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation=handle_events(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
            else:
                pass
            
            if offset_x+ width_x > mouse_clicked[0] > offset_x and (5*offset_y+ int((2/60)*height) + width_y) > mouse_clicked[1] > (5*offset_y+ int((2/60)*height)):
                if images_first_screen_dict.get('neue_animation').state == True:
                    pass                
                
                elif images_first_screen_dict.get('neue_animation').state == False:                
                    images_first_screen_dict.get('animationswahl').state = True
                    mode = 'mode1'
                    pygame.draw.rect(screen, weiss, (offset_x, 5*offset_y+ int((2/60)*height), width_x, width_y), 2) 
                
                    for boxes in range(len(images_first_screen)):
                        if images_first_screen[boxes] == 'animationswahl':
                            pass
                        else:
                            images_first_screen_dict.get(images_first_screen[boxes]).state = False  
                
            
            elif offset_x+ width_x > mouse_clicked[0] > offset_x and (4*offset_y+ int((2/60)*height)+width_y) > mouse_clicked[1] > (4*offset_y+ int((2/60)*height)):
                if images_first_screen_dict.get('neue_animation').state == True:
                    pass                
                
                elif images_first_screen_dict.get('neue_animation').state == False:
                
                    images_first_screen_dict.get('neue_animation').state = True
                    mode = 'mode2'
                
                    for boxes in range(len(images_first_screen)):
                        if images_first_screen[boxes] == 'neue_animation':
                            pass
                        else:
                            images_first_screen_dict.get(images_first_screen[boxes]).state = False
                
            
            elif offset_x+ width_x > mouse_clicked[0] > offset_x and (3*offset_y+ int((2/60)*height)+width_y) > mouse_clicked[1] > (3*offset_y+ int((2/60)*height)):
                if images_first_screen_dict.get('neue_animation').state == True:
                    pass
                elif images_first_screen_dict.get('neue_animation').state == False:
                
                    images_first_screen_dict.get('zeit_intervall').state = True
                    mode = 'mode1'
                    pygame.draw.rect(screen, weiss, (offset_x, 3*offset_y+ int((2/60)*height), width_x, width_y), 2)
                
                    for boxes in range(len(images_first_screen)):
                        if images_first_screen[boxes] == 'zeit_intervall':
                            pass
                        else:
                            images_first_screen_dict.get(images_first_screen[boxes]).state = False 
                
                
            
            elif offset_x+ width_x > mouse_clicked[0] > offset_x and (2*offset_y+ int((2/60)*height)+width_y) > mouse_clicked[1] > (2*offset_y+ int((2/60)*height)):
                if images_first_screen_dict.get('neue_animation').state == True:
                    images_second_screen_dict.get('exit').state = True
                    mode = 'mode1'
                   
                    for boxes2 in range(len(images_second_screen)):
                        if images_second_screen[boxes2] == 'exit':
                            pass
                        else:
                            images_second_screen_dict.get(images_second_screen[boxes2]).state = False
                    
                
                elif images_first_screen_dict.get('neue_animation').state == False:
                    images_first_screen_dict.get('Stop').state = True
                    mode = 'mode1'
                    pygame.draw.rect(screen, weiss, (offset_x, 2*offset_y+ int((2/60)*height), width_x, width_y), 2)
                    
                    for boxes in range(len(images_first_screen)):
                        if images_first_screen[boxes] == 'Stop':
                            pass
                        else:
                            images_first_screen_dict.get(images_first_screen[boxes]).state = False
                    
                              
            
            elif offset_x+ width_x > mouse_clicked[0] > offset_x and (1*offset_y+ int((2/60)*height)+width_y) > mouse_clicked[1] > (1*offset_y+ int((2/60)*height)):
                if images_first_screen_dict.get('neue_animation').state == True:
                    images_second_screen_dict.get('animation_speichern').state = True
                    mode = 'mode2'
                    if animation == 'neueanimation.txt':
                        pygame.draw.rect(screen, gruen, (offset_x, 1*offset_y+ int((2/60)*height), width_x, width_y), 3)
                    else:
                        pygame.draw.rect(screen, rot, (offset_x, 1*offset_y+ int((2/60)*height), width_x, width_y), 4)
                        
                    
                    
                    
                    for boxes2 in range(len(images_second_screen)):
                        if images_second_screen[boxes2] == 'animation_speichern':
                            pass
                        else:
                            images_second_screen_dict.get(images_second_screen[boxes2]).state = False
                    
                
                elif images_first_screen_dict.get('neue_animation').state == False:
                    images_first_screen_dict.get('start_animation').state = True
                    mode = 'mode1'
                    pygame.draw.rect(screen, weiss, (offset_x, 1*offset_y+ int((2/60)*height), width_x, width_y), 2)

                    for boxes in range(len(images_first_screen)):
                        if images_first_screen[boxes] == 'start_animation':
                            pass
                        else:
                            images_first_screen_dict.get(images_first_screen[boxes]).state = False
                    
                  
            
            elif offset_x+ width_x > mouse_clicked[0] > offset_x and (0*offset_y+ int((2/60)*height)+width_y) > mouse_clicked[1] > (0*offset_y+ int((2/60)*height)):
                if images_first_screen_dict.get('neue_animation').state == True:
                    images_second_screen_dict.get('bild_speichern').state = True
                    mode = 'mode2'
                    pygame.draw.rect(screen, weiss, (offset_x, 0*offset_y+ int((2/60)*height), width_x, width_y), 2)
                    for boxes2 in range(len(images_second_screen)):
                        if images_second_screen[boxes2] == 'bild_speichern':
                            pass
                        else:
                            images_second_screen_dict.get(images_second_screen[boxes2]).state = False
                    
                
                elif images_first_screen_dict.get('neue_animation').state == False:
                    images_first_screen_dict.get('start_schrift').state = True
                    mode = 'mode1'
                    pygame.draw.rect(screen, weiss, (offset_x, 0*offset_y+ int((2/60)*height), width_x, width_y), 2)
                    for boxes in range(len(images_first_screen)):
                        if images_first_screen[boxes] == 'start_schrift':
                            pass
                        else:
                            images_first_screen_dict.get(images_first_screen[boxes]).state = False
        
        if drag == True and images_first_screen_dict.get('neue_animation').state == True:
            mouse = pygame.mouse.get_pos()
            
            drag = True
        
        
        if drag == True and images_first_screen_dict.get('zeit_intervall').state == True: 
            pygame.draw.rect(screen, weiss, (offset_x, 3*offset_y+ int((2/60)*height), width_x, width_y), 2)
            mouse = pygame.mouse.get_pos()
            
            
            if (int(width*(9/11))*0.25)-1>=mouse[0]:
                slider_value = (screen, (255,255,0), (int(width* (9/11) *0.25), int(height/2)), int(height*0.05),0)
                time_value = 0.02
                    
            elif mouse[0]>=(int(width*(9/11))*0.75)+1:
                slider_value = (screen, (255,255,0), (int(width*(9/11) *0.75), int(height/2)), int(height*0.05),0)
                time_value = 2
                            
            else:          
                slider_value = (screen, (255,255,0), (int(mouse[0]), int(height/2)), int(height*0.05),0)
                time_value= (0.000672*((float(mouse[0])-int(width*(9/11))*0.25)*(100/int(width*(9/11))))**2)+(0.006*((float(mouse[0])-int(width*(9/11))*0.25)*(100/int(width*(9/11))))+ 0.02)      
                
            drag = True
            
        
        if event.type == pygame.MOUSEBUTTONUP:
            drag = False             
       
    return arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation
                                 
                
slider_value = None
slider_background = None
          
buttons.load_images('mode1') 
buttons.load_images('mode2') 
mode = 'mode1'                                                      
mouse= (0,0) 
mouse_clicked =(0,0)
LedFont.init_circles()
for button in images_first_screen:
    
    screen.blit(images_first_screen_dict.get(button).image, images_first_screen_dict.get(button).position)

    
pygame.display.update() 

while True:
    
    
    mode_before = mode
    mouse_before = mouse_clicked
    arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation = handle_events(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
    mouse_after = mouse_clicked
    if mouse_before == mouse_after:
        mouse_clicked= None
    mode_after = mode
    
    if mode_before != mode_after:
        screen.fill(schwarz)
        if screen_choose.get(mode) == 'images_first_screen':
            for button in images_first_screen:
                screen.blit(images_first_screen_dict.get(button).image, images_first_screen_dict.get(button).position)
        elif screen_choose.get(mode) == 'images_second_screen': 
            for button in images_second_screen:
                screen.blit(images_second_screen_dict.get(button).image, images_second_screen_dict.get(button).position) 
        pygame.display.update()
    else:
        pass
    time.sleep(0.02)
    arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation = buttons.check_state(arrayled, mode, mouse_clicked, mouse, color_chosen, time_value, slider_value, drag, animation)
    
    
                        
                    
                    
                    
                        
