#General purpose libraries
import time
import numpy as np
import csv
from scipy.signal import find_peaks

#Gui Libraries
import tkinter as tk
from tkinter import ttk
from tkinter.constants import CENTER, TRUE
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from PIL import ImageTk, Image
import tkcalendar

#A/D Conversor Libraries
import board
import busio
import adafruit_ads1x15.ads1015 as ADS
from adafruit_ads1x15.analog_in import AnalogIn

#Sensor Libraries
from w1thermsensor import W1ThermSensor
from heartrate_monitor import HeartRateMonitor

## Sensor Initializing ##
# Temp
sensor_temperatura = W1ThermSensor()
# BPM y SPO2
bpm_ox = HeartRateMonitor()
bpm_ox.start_sensor()
# A/D: FR y ECG
i2c = busio.I2C(board.SCL, board.SDA)
ads = ADS.ADS1015(i2c)
data_ecg = AnalogIn(ads, ADS.P0)
data_fr = AnalogIn(ads, ADS.P1)


# Graph Constant 
lim_ecg = [0, 6, 0, 2]
lim_fr = [0, 30, 0, 4]
grid_ecg_y0 = list(np.linspace(0, 2, 5))
grid_ecg_y1 = list(np.linspace(0.1, 2, 20))
grid_ecg_x1 = list(np.linspace(0.1, 6, 60))
grid_ecg_x0 = list(np.linspace(0, 6, 13))
is_play = True
x1 = list(np.linspace(0,6,150))
x2 = list(np.linspace(0,30,150))
y1 = list(np.zeros(150))
y2 = list(np.zeros(150))

# Alarm Constant
temp1='37'
temp2='39'
bpm1='60'
bpm2='100' 
spo2='80'
fr1='5'
fr2='40'

# Sensor Variable
bpm_list = []
ox_list = []
temp_list = []
fr_list = list(np.zeros(150))
ecg_list = list(np.zeros(150))
bpm_mean = 80
ox_mean = 90
temp_mean = 36
fr_mean = 20
ecg_mean = 30
fecha = time.strftime('%d/%m/%Y', time.localtime())
hora = time.strftime('%H:%M:%S', time.localtime())

# FONTS
topfont = 'Courier 10'
labelxfont = {'family':'tahoma','size':'8', 'color':'#50d0c3'}
labelyfont = {'family':'tahoma','size':'10', 'color':'#50d0c3'}
font1 = 'Courier 12'
font2 = 'Courier 15'
font3 = 'Courier 30'
font4 = 'Courier 15 bold'
font5 = 'Courier 18 underline bold'
font6 = 'Courier 20 bold'

# General Variables
Problema = 'ESTADO'
pa1 = 'SYS'
pa2 = 'DIA'
name = 'Sheridan Santiago'
password = '12345'

## FUNCTION ##
def actualizar_hora():
    global fecha, hora
    fecha = time.strftime('%d/%m/%Y', time.localtime())
    hora = time.strftime('%H:%M:%S', time.localtime())
    label_fecha.configure(text=(hora+'  '+fecha))
    estado()
    '''
    #BPM y SPO2
    if len(bpm_list) != 0 and len(ox_list) != 0:
        bpm_mean = sum(bpm_list)/len(bpm_list)
        ox_mean = sum(ox_list)/len(ox_list)
    label_bpm.config(text=str(round(bpm_mean,2))+'bpm')
    label_ox.config(text=str(round(ox_mean,2))+'%')   

    #Temperatura
    if len(temp_list) != 0:
        temp_mean = sum(temp_list)/len(temp_list)
    label_temperatura.config(text=temp_mean)

    #FR
    '''
    frame_top2.after(1000, actualizar_hora)
    
def actualizar_ox():
    data_ox = bpm_ox.get_data()
    bpm_list.append(data_ox["bpm"])
    ox_list.append(data_ox["spo2"])
    if len(bpm_list) > 20:
        bpm_list.pop(0)
        ox_list.pop(0)

    frame_ox.after(1000, actualizar_ox)

def actualizar_temp():
    t = sensor_temeratura.get_temperature()
    temp_list.append(t)
    if len(temp_list) > 10:
        temp_list.pop(0)
    frame_temp.after(5000, actualizar_temp)

def play_pause():
    global is_play
    if is_play:
        ani_fr.pause()
        ani_ecg.pause()
        play_pause_button.config(image=play_icon)
        is_play = False
    else:
        ani_fr.resume()
        ani_ecg.resume()
        play_pause_button.config(image=pause_icon)
        is_play = True 

def pedir_contraseña():
    def botonsito():
        if password == var.get():
            bpm_ox.stop_sensor()
            root.quit()
        else:
            var.set('Incorrecta')
            
    ventana = tk.Toplevel(root)
    ventana.geometry('198x48+601+406')
    ventana.config(bg='black')
    ventana.resizable(0, 0)
    ventana.overrideredirect(True)
    var = tk.StringVar()
    c = tk.Entry(ventana, textvariable=var).place(x=10, y=8, width=80,height=30)
    c_boton = tk.Button(ventana, image=check_icon, command=botonsito,bg='black', activebackground='#50d0c3',relief='groove').place(x=110, y=9)
    q_boton = tk.Button(ventana, image=x_icon, command=ventana.destroy,bg='black', activebackground='#50d0c3',relief='groove').place(x=150, y=9)

def plotfr(i):
    global fr_mean, fr_list
    fr_mean = data_fr.voltage
    fr_list.append(fr_mean)
    if len(fr_list) > 150:
        y2.pop(0)
    linea_fr.set_data(x2, fr_list)
    return linea_fr,

def plotecg(j):
    global ecg_mean, ecg_list
    ecg_mean = data_ecg.voltage
    ecg_list.append(ecg_mean)
    if len(ecg_list) > 150:
        y1.pop(0)
    linea_ecg.set_data(x1, ecg_list)
    return linea_ecg,

def alarma():
    ## Funciones ##
    def silenciar():
        a=2
    def salir():
        global temp1, temp2, bpm1, bpm2, spo2, fr1, fr2
        temp1 = temp1_spin.get()
        temp2 = temp2_spin.get()
        bpm1 = bpm1_spin.get()
        bpm2 = bpm2_spin.get()
        spo2 = spo2_spin.get()
        fr1 = fr1_spin.get()
        fr2 = fr2_spin.get()
        alarma_root.destroy()
    ## Root ##
    alarma_root = tk.Toplevel(root)
    alarma_root.geometry('800x480+0+0')
    alarma_root.config(bg='black', bd=5, relief='groove')
    alarma_root.resizable(0, 0)
    alarma_root.overrideredirect(True)
    ## Frames ##
    frame_1 = tk.Frame(alarma_root, bg = 'black', relief='groove', bd=2).place(x=0,y=0,width=790,height=80)
    frame_2 = tk.Frame(alarma_root, bg = 'black', relief='groove', bd=2).place(x=0,y=80,width=790,height=80)
    frame_3 = tk.Frame(alarma_root, bg = 'black', relief='groove', bd=2).place(x=0,y=160,width=790,height=80)
    frame_4 = tk.Frame(alarma_root, bg = 'black', relief='groove', bd=2).place(x=0,y=240,width=790,height=80)
    frame_5 = tk.Frame(alarma_root, bg = 'black', relief='groove', bd=2).place(x=0,y=320,width=790,height=80)
    frame_6 = tk.Frame(alarma_root, bg = 'black', relief='groove', bd=2).place(x=0,y=400,width=790,height=70)
    ## Labels ##
    config_Label = tk.Label(alarma_root, text='Configuracion de Alarma',font=font5, bg='black', fg='turquoise1').place(x=35, y=25)
    max_Label = tk.Label(alarma_root, text='Maximo',font=font4, bg='black', fg='turquoise1').place(x=610, y=30)
    min_Label = tk.Label(alarma_root, text='Minimo',font=font4, bg='black', fg='turquoise1').place(x=410, y=30)
    temp_Label = tk.Label(alarma_root, text='Temperatura:',font=font2, bg='black', fg='turquoise1').place(x=50, y=110)
    bpm_Label = tk.Label(alarma_root, text='BPM:',font=font2, bg='black', fg='turquoise1').place(x=50,y=190)
    spo2_Label = tk.Label(alarma_root, text='SPO2:',font=font2, bg='black', fg='turquoise1').place(x=50,y=270)
    fr_Label = tk.Label(alarma_root, text='Frecuencia Respiratoria:',font=font2, bg='black', fg='turquoise1').place(x=50,y=350)
    ## StringVar ##
    temp1_var = tk.StringVar(alarma_root)
    temp1_var.set(temp1)
    temp2_var = tk.StringVar(alarma_root)
    temp2_var.set(temp2)
    bpm1_var = tk.StringVar(alarma_root)
    bpm1_var.set(bpm1)
    bpm2_var = tk.StringVar(alarma_root)
    bpm2_var.set(bpm2)
    spo2_var = tk.StringVar(alarma_root)
    spo2_var.set(spo2)
    fr1_var = tk.StringVar(alarma_root)
    fr1_var.set(fr1)
    fr2_var = tk.StringVar(alarma_root)
    fr2_var.set(fr2)
    ## Spinbox ##
    temp1_spin = tk.Spinbox(alarma_root, from_=20, to=45,textvariable=temp1_var,increment=0.1, bg='black',fg='turquoise1', width=4, font=font3,justify=CENTER, buttonbackground='black')
    temp1_spin.place(x=400,y=95)
    temp2_spin = tk.Spinbox(alarma_root,from_=20, to=45,textvariable=temp2_var,increment=0.1,bg='black',fg='turquoise1',width=4,font=font3,justify=CENTER, buttonbackground='black')
    temp2_spin.place(x=600,y=95)
    bpm1_spin = tk.Spinbox(alarma_root, from_=40, to=150,textvariable=bpm1_var, bg='black',fg='turquoise1', width=3, font=font3,justify=CENTER, buttonbackground='black')
    bpm1_spin.place(x=400,y=175)
    bpm2_spin = tk.Spinbox(alarma_root,from_=40, to=150,textvariable=bpm2_var,bg='black',fg='turquoise1',width=3,font=font3,justify=CENTER, buttonbackground='black')
    bpm2_spin.place(x=600,y=175)
    spo2_spin = tk.Spinbox(alarma_root, from_=70, to=100,textvariable=spo2_var, bg='black',fg='turquoise1', width=3, font=font3,justify=CENTER, buttonbackground='black')
    spo2_spin.place(x=400,y=255)
    fr1_spin = tk.Spinbox(alarma_root, from_=0, to=80,textvariable=fr1_var, bg='black',fg='turquoise1', width=3, font=font3,justify=CENTER, buttonbackground='black')
    fr1_spin.place(x=400,y=335)
    fr2_spin = tk.Spinbox(alarma_root,from_=0, to=80,textvariable=fr2_var,bg='black',fg='turquoise1',width=3,font=font3,justify=CENTER, buttonbackground='black')
    fr2_spin.place(x=600,y=335)
    ## Button ##
    bell_boton = tk.Button(alarma_root, image=belloff_icon, command=silenciar ,bg='black', activebackground='#50d0c3',relief='groove').place(x=300, y=415)
    back_boton = tk.Button(alarma_root, image=back_icon, command=salir, bg='black', activebackground='#50d0c3',relief='groove').place(x=500, y=415)

def estado():
    global temp1, temp2, bpm1, bpm2, spo2, fr1, fr2
    if temp_mean < float(temp1):
        temp_str = "Principio de Hipotermia"
    elif temp_mean > float(temp2):
        temp_str = "Fiebre"
    else:
        temp_str = "T° Normal"
    if bpm_mean < float(bpm1):
        bpm_str = "Bradicardia"
    elif bpm_mean > float(bpm2):
        bpm_str = "Taquicardia"
    else:
        bpm_str = "BPM Normal"
    if  fr_mean < float(fr1):
        fr_str ="Bradipnea"
    elif fr_mean > float(fr2):
        fr_str = "Taquipnea"
    else:
        fr_str = "FR Normal"
    if ox_mean < float(spo2):
        ox_str = "Hipoxemia"
    else: 
        ox_str = "SPO2 Normal"
    
    label_problema.config(text=(temp_str + " | " + bpm_str + " | " + fr_str + " | " + ox_str))

def historial():
    def limpiar():
        a = tree_historial.get_children()
        for row in a:
            tree_historial.delete(row)
    
    def seleccionar_fecha(evento):
        fecha_inicio_pick = str(fecha_inicio.get_date())
        fecha_inicio_pick = fecha_inicio_pick.split(sep='-')
        fecha_fin_pick = str(fecha_fin.get_date())
        fecha_fin_pick = fecha_fin_pick.split(sep='-')
        cuenta = 0

        with open('data.csv', 'r') as data:
            csv_r = csv.reader(data)
            for row in csv_r:
                fecha_row = row[0].split(sep='/')
                if int(fecha_inicio_pick[0]) <= int(fecha_row[2]) <= int(fecha_fin_pick[0]):
                    if (int(fecha_inicio_pick[1]) <= int(fecha_row[1]) <= int(fecha_fin_pick[1])) or (int(fecha_inicio_pick[0]) < int(fecha_row[2])):
                        if (int(fecha_inicio_pick[2]) <= int(fecha_row[0]) <= int(fecha_fin_pick[2])) or (int(fecha_inicio_pick[1]) < int(fecha_row[1]) and int(fecha_row[0]) <= int(fecha_fin_pick[2])):
                            cuenta = (cuenta + 1) % 2
                            if cuenta == 0:
                                tree_historial.insert(parent='',index=0,values=(row[0], row[1], row[2], row[3], row[4], row[5]),tags=('claro',))
                            else:
                                tree_historial.insert(parent='',index=0,values=(row[0], row[1], row[2], row[3], row[4], row[5]),tags=('oscuro',))

    ##Root##
    historial_root = tk.Toplevel(root)
    historial_root.geometry('800x480+0+0')
    historial_root.config(bg='black', bd=5, relief='groove')
    historial_root.resizable(0, 0)
    historial_root.overrideredirect(True)
    ## Frames ##
    frame_treetop = tk.Frame(historial_root,bg='black')
    frame_treetop.place(x=0, y=0, height=70, width=790)
    frame_tree = tk.Frame(historial_root, bg='black')
    frame_tree.place(x=50, y=70, height=320, width=700)
    ## Styles ##
    style = ttk.Style()
    style.theme_use('default')
    style.configure('Vertical.TScrollbar', arrowsize=30)
    ## widget ##
    label_historial = tk.Label(frame_treetop, text='Historial', font=font5, bg='black', fg='turquoise1')
    label_historial.place(x=55,y=20)
    label_fecha_inicio = tk.Label(frame_treetop, text='Inicio:', font=font2, bg='black', fg='turquoise1')
    label_fecha_inicio.place(x=305, y=25)
    label_fecha_fin = tk.Label(frame_treetop, text='Fin:', font=font2, bg='black', fg='turquoise1')
    label_fecha_fin.place(x=500, y=25)

    tree_historial = ttk.Treeview(frame_tree,show='headings',selectmode='browse')
    tree_historial.tag_configure('oscuro', background='#50d0c3',foreground='red')
    tree_historial.tag_configure('claro', background='red',foreground='blue')
    tree_historial.pack(side='left', fill='both')
    
    tree_bar = ttk.Scrollbar(frame_tree, orient='vertical', command=tree_historial.yview)
    tree_bar.pack(side='right', fill='y')
    tree_historial.configure(yscrollcommand=tree_bar.set)

    clean_boton = tk.Button(historial_root, image=clean_icon, command=limpiar ,bg='black', activebackground='#50d0c3',relief='groove').place(x=300, y=415)
    back_boton = tk.Button(historial_root, image=back_icon, command=historial_root.destroy, bg='black', activebackground='#50d0c3',relief='groove').place(x=500, y=415)

    fecha_inicio = tkcalendar.DateEntry(frame_treetop, width=8, year=2022, month=3, background='darkblue', foreground='white', borderwidth=2)
    fecha_inicio.config(background='#50d0c3', font=font1)
    fecha_inicio.place(x=390, y=28)
    fecha_inicio.bind("<<DateEntrySelected>>", seleccionar_fecha)
    fecha_fin = tkcalendar.DateEntry(frame_treetop, width=8, year=2022, month=3, background='darkblue', foreground='white', borderwidth=2)
    fecha_fin.config(background='#50d0c3', font=font1)
    fecha_fin.place(x=550, y=28)
    fecha_fin.bind("<<DateEntrySelected>>", seleccionar_fecha)

    tree_historial['columns'] = ('F','H','T','FR', 'SPO2', 'BPM')
    tree_historial.column('F',width=105,minwidth=105,anchor=CENTER)
    tree_historial.column('H',width=105,minwidth=105,anchor=CENTER)
    tree_historial.column('T',width=105,minwidth=105,anchor=CENTER)
    tree_historial.column('FR',width=145,minwidth=145,anchor=CENTER)
    tree_historial.column('SPO2',width=105,minwidth=105,anchor=CENTER)
    tree_historial.column('BPM',width=105,minwidth=105,anchor=CENTER)

    tree_historial.heading('F', text='Fecha')
    tree_historial.heading('H', text='Hora')
    tree_historial.heading('T', text='Temperatura [°C]')
    tree_historial.heading('FR',text='Frecuencia Respiratoria')
    tree_historial.heading('SPO2',text='SPO2')
    tree_historial.heading('BPM',text='BPM')

def guardar_csv():
    fecha = time.strftime('%d/%m/%Y', time.localtime())
    hora = time.strftime('%H:%M:%S', time.localtime())
    with open('data.csv', 'a', newline='') as data:
        csv_w = csv.writer(data, delimiter=',')
        csv_w.writerow([fecha, hora, temp_mean, fr_mean, ox_mean, bpm_mean])


# ROOT WINDOW
root = tk.Tk()
root.attributes('-fullscreen',True)
root.resizable(0,0)
root.geometry('800x480')
root.config(bg='#50d0c3')

# ICONS
set_icon = ImageTk.PhotoImage(Image.open('./Icon/settings (2).png'))
play_icon = ImageTk.PhotoImage(Image.open('./Icon/play.png'))
pause_icon = ImageTk.PhotoImage(Image.open('./Icon/pause.png'))
heart_icon = ImageTk.PhotoImage(Image.open('./Icon/heart.png'))
therm_icon = ImageTk.PhotoImage(Image.open('./Icon/therm.png'))
x_icon = ImageTk.PhotoImage(Image.open('./Icon/x.png'))
back_icon = ImageTk.PhotoImage(Image.open('./Icon/arrow.png'))
clean_icon = ImageTk.PhotoImage(Image.open('./Icon/trash.png'))
check_icon = ImageTk.PhotoImage(Image.open('./Icon/check.png'))
bell_icon = ImageTk.PhotoImage(Image.open('./Icon/bell (1).png'))
belloff_icon = ImageTk.PhotoImage(Image.open('./Icon/bell-off (1).png'))
historial_icon = ImageTk.PhotoImage(Image.open('./Icon/list (1).png'))
#act_icon = ImageTk.PhotoImage(Image.open('./Icon/home.png'))
#wind_icon = ImageTk.PhotoImage(Image.open('./Icon/home.png'))

## Frames ##
# Graph 
frame_ecg = tk.Frame(root, bg = 'black', relief='groove', bd=1)
frame_fr = tk.Frame(root, bg = 'black', relief='groove', bd=1)
# Sensors
frame_ox = tk.Frame(root, bg='black', relief='groove',bd=1)
frame_bpm = tk.Frame(root, bg='black', relief='groove', bd=1)
frame_temp = tk.Frame(root, bg='black', relief='groove', bd=1)
frame_pa = tk.Frame(root, bg='black', relief='groove', bd=1)
# Button
frame_button = tk.Frame(root, bg='black', relief='groove', bd=1)
# Labels
frame_top1 = tk.Frame(root, bg='black', relief='groove', bd=1)
frame_top2 = tk.Frame(root, bg='black', relief='groove', bd=1)
frame_bot = tk.Frame(root, bg='black', relief='groove', bd=1)

## Labels ##
# TOP
label_problema = tk.Label(frame_top1, text=Problema, font=topfont, bg='black', fg='turquoise1')
label_fecha = tk.Label(frame_top2, text='', font=topfont, bg='black', fg='turquoise1')
# BOT
label_bot = tk.Label(frame_bot,text=name, font=topfont, bg='black', fg='turquoise1')
# Temp
label_temperatura = tk.Label(frame_temp, text='--', font=font3, bg='black', fg='turquoise1')
label_temperatura2 = tk.Label(frame_temp, text='TEMP', font=font2, bg='black', fg='turquoise1')
label_temperatura3 = tk.Label(frame_temp, text='°C', font=font2, bg='black', fg='turquoise1')
label_temperatura4 = tk.Label(frame_temp, image=therm_icon, font=font2, bg='black', fg='turquoise1')
# BPM
label_bpm = tk.Label(frame_bpm, text='--', font=font3, bg='black', fg='turquoise1')
label_bpm2 = tk.Label(frame_bpm, text='BPM', font=font2, bg='black', fg='turquoise1')
label_bpm3 = tk.Label(frame_bpm, image=heart_icon, fg = 'black', bg = 'black')
label_bpm4 = tk.Label(frame_bpm, text='rpm', font=font2, bg='black', fg='turquoise1')
# SPO2
label_ox = tk.Label(frame_ox, text='--', font=font3, bg='black', fg='turquoise1')
label_ox2 = tk.Label(frame_ox, text='SPO2', font=font2, bg='black', fg='turquoise1')
label_ox3 = tk.Label(frame_ox, text='%', font='Helvetica 15', bg='black', fg='turquoise1')
label_ox4 = tk.Label(frame_ox, text='O\u2082', font=font6, bg='black', fg='turquoise1')
# PA
label_pa = tk.Label(frame_pa, text=pa1, font=font6, bg='black', fg='turquoise1')
label_pa2 = tk.Label(frame_pa, text=pa2, font=font6, bg='black', fg='turquoise1')
label_pa3 = tk.Label(frame_pa, text='mmHg', font=font2, bg='black', fg='turquoise1')
label_pa4 = tk.Label(frame_pa, text='SYS:', font=font2, bg='black', fg='turquoise1')
label_pa5 = tk.Label(frame_pa, text='DIA:', font=font2, bg='black', fg='turquoise1')
label_pa6 = tk.Label(frame_pa, text='PA', font=font2, bg='black', fg='turquoise1')

## Graph ##
plt.style.use('dark_background')
plt.tight_layout()
figure_ecg, ecg = plt.subplots(1,1, figsize=(5.9,2.05),sharex='all',sharey='all')
figure_fr, fr = plt.subplots(1,1, figsize=(5.9,2.05), sharex='all',sharey='all')

# plot ecg - config
linea_ecg, = ecg.plot(x1, y1)
ecg.set_ylabel('Amplitud',loc='center',rotation='vertical', fontdict = labelyfont)
ecg.set_title('Electrocardiograma', loc='center' ,fontdict = labelyfont)
ecg.tick_params(axis='x', colors='#50d0c3', labelsize=7)
ecg.tick_params(axis='y', colors='#50d0c3', labelsize=7)
ecg.spines['bottom'].set_color('#50d0c3')
ecg.spines['top'].set_color('#50d0c3')
ecg.spines['right'].set_color('#50d0c3')
ecg.spines['left'].set_color('#50d0c3')
ecg.set_ylim([lim_ecg[2], lim_ecg[3]])
ecg.set_xlim([lim_ecg[0], lim_ecg[1]])
ecg.set_yticks(grid_ecg_y0, minor=False)
ecg.set_yticks(grid_ecg_y1, minor=True)
ecg.set_xticks(grid_ecg_x0, minor=False)
ecg.set_xticks(grid_ecg_x1, minor=True)
ecg.grid(True,color='#50d0c3',linestyle='--',linewidth=0.3, which='minor')
ecg.grid(True,color='#50d0c3',linewidth=0.7,linestyle='--',which='major')


# plot PA - config
linea_fr, = fr.plot(x2, y2)
fr.set_title('Frecuencia Respiratoria', loc='center', fontdict=labelyfont)
fr.set_ylabel('Respiraciones',loc='center',rotation='vertical', fontdict = labelyfont)
fr.tick_params(axis='x', colors='#50d0c3', labelsize=7)
fr.tick_params(axis='y', colors='#50d0c3', labelsize=7)
fr.spines['bottom'].set_color('#50d0c3')
fr.spines['top'].set_color('#50d0c3')
fr.spines['right'].set_color('#50d0c3')
fr.spines['left'].set_color('#50d0c3')
fr.set_ylim([lim_fr[2], lim_fr[3]])
fr.set_xlim([lim_fr[0], lim_fr[1]])

#Canvas
ecg_canvas = FigureCanvasTkAgg(figure_ecg, master=frame_ecg)
fr_canvas = FigureCanvasTkAgg(figure_fr, master=frame_fr)


## BUTTON ##
set_button = tk.Button(frame_button,image=set_icon, command=pedir_contraseña, fg = 'black', bg = 'black', activebackground='#50d0c3',relief='groove')
play_pause_button = tk.Button(frame_button,command=play_pause, image=pause_icon, fg = 'black', bg = 'black', activebackground='#50d0c3',relief='groove')
bell_button = tk.Button(frame_button, command=alarma, image=bell_icon, fg='black', bg='black', activebackground='#50d0c3',relief='groove')
historial_button = tk.Button(frame_button, command=historial, image=historial_icon, fg='black',bg='black', activebackground='#50d0c3',relief='groove')

## PLACES ##

# FRAMES #

# TOP - BOT
frame_top1.place(x=0, y=0, width=600, height=25)
frame_top2.place(x=600, y=0,width=200, height=25)
frame_bot.place(x=0,y=455, width=800, height=25)
# Right Column
frame_ox.place(x=600, y=25, width=200, height=95)
frame_bpm.place(x=600, y=120, width=200, height=95)
frame_temp.place(x=600, y=215, width=200, height=95)
frame_pa.place(x=600, y=310, width=200, height=95)
frame_button.place(x=600, y=405, width=200, height=50)
# Graph
frame_ecg.place(x=0, y=25, width=600, height=215)
frame_fr.place(x=0, y=240, width=600, height=215)
ecg_canvas.get_tk_widget().place(x=0, y=0)
fr_canvas.get_tk_widget().place(x=0, y=0)

# LABELS #

#TOP
label_problema.place(x=0, y=0, width=594, height=18)
label_fecha.place(x=0, y=0, width=194, height=18)
#BOT
label_bot.place(x=0, y=0, width=790, height=18)
#BPM
label_bpm.place(x=50, y=20, width=100, height=60)
label_bpm2.place(x=0, y=0)
label_bpm3.place(x=158, y=3)
label_bpm4.place(x=140, y=50)
#OX
label_ox.place(x=50, y=20, width=100, height=60)
label_ox2.place(x=0, y=0)
label_ox3.place(x=145, y=55)
label_ox4.place(x=154, y=0)
#TEMP
label_temperatura.place(x=50, y=20, width=100, height=60)
label_temperatura2.place(x=0, y=0)
label_temperatura3.place(x=145, y=55)
label_temperatura4.place(x=160, y=5)
#PR
label_pa.place(x=75, y=20)
label_pa2.place(x=75, y=50)
label_pa3.place(x=135, y=60)
label_pa4.place(x=25, y=25)
label_pa5.place(x=25, y=55)
label_pa6.place(x=0, y=0)

# BUTTONS #
play_pause_button.place(x=5, y=4)
bell_button.place(x=55, y=4)
historial_button.place(x=105, y=4)
set_button.place(x=155, y=4)


## ON ##
actualizar_hora()
actualizar_temp()
actualizar_ox()
ani_fr = animation.FuncAnimation(figure_fr, plotfr, interval=100, blit=True)
ani_ecg = animation.FuncAnimation(figure_ecg, plotecg, interval=10, blit=True)

root.mainloop()
