import tkinter as tk
from tkinter import messagebox,simpledialog
from tkinter import ttk
import json
import aux_function
import sys
import psycopg2 as psql
import cv2 
import webbrowser
from win32api import GetSystemMetrics
import psycopg2.extras
import numpy as np
import time
import os
import base64

class Roi():
    def __init__(self, rampa):
        self.wd=GetSystemMetrics(0)
        self.he=GetSystemMetrics(1)
        self.rampa = rampa

        db = cfg['db']
        try:
            self.conn = psycopg2.connect(db)
            self.conn.autocommit = True
        except:
            print ("I am unable to connect to the database")

        self.cursor = self.conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
        refPt = []
        cropping = False
        webbrowser.open(cfg['RUTAS']['roi']+"?ras="+str(rampa), new=2, autoraise=True)
    def start(self):
        fcam1=self.hacerfoto(self.rampa)
        if(fcam1 is not None):
            self.image = fcam1

            cv2.namedWindow("Layout Creator", cv2.WINDOW_FULLSCREEN)
            cv2.moveWindow('Layout Creator', 400, 0)
            cv2.setMouseCallback("Layout Creator", self.ver_xy)


            while True:
                cv2.namedWindow("Layout Creator", cv2.WINDOW_AUTOSIZE)
                cv2.imshow("Layout Creator", self.image)
                key = cv2.waitKey(1) & 0xFF

                if key == ord("r") or key == ord("R"):                        # Reset foto
                    fcam1=self.hacerfoto(self.rampa)
                    self.image = fcam1
                if key == ord("a") or key == ord("A"):                        # Zona de la caja
                    if len(refPt) == 2:
                        self.gestiona_xy (refPt)
                if key == ord("b") or key == ord("B"):                        # Zona de sensibilidad
                    if len(refPt) == 2:
                        self.gestiona_x1y1 (refPt)
                if key == ord("c") or key == ord("C"):                        # Zona de sensibilidad
                    if len(refPt) == 2:
                        self.gestiona_x2y2 (refPt)
                if key == ord("d") or key == ord("D"):                        # Zona de sensibilidad
                    if len(refPt) == 2:
                        self.gestiona_x3y3 (refPt)
                if key == ord("e") or key == ord("E"):                        # Zona de sensibilidad
                    if len(refPt) == 2:
                        self.gestiona_x4y4 (refPt)
                if key == ord("i") or key == ord("I"):                        # Zona de sensibilidad extendida
                    if len(refPt) == 2:
                        self.gestiona_x1y1_ext (refPt)
                if key == ord("j") or key == ord("J"):                        # Zona de sensibilidad extendida
                    if len(refPt) == 2:
                        self.gestiona_x2y2_ext (refPt)
                if key == ord("k") or key == ord("K"):                        # Zona de sensibilidad extendida
                    if len(refPt) == 2:
                        self.gestiona_x3y3_ext (refPt)
                if key == ord("l") or key == ord("L"):                        # Zona de sensibilidad extendida
                    if len(refPt) == 2:
                        self.gestiona_x4y4_ext (refPt)
                if key == ord("f") or key == ord("F"):                        # Zona de textos producto y pedido
                    if len(refPt) == 2:
                        self.gestiona_txty (refPt)
                        self.gestiona_bxby (refPt)
                if key == ord("g") or key == ord("G"):                        # Origen de la linea
                    if len(refPt) == 2:
                        self.gestiona_orilin (refPt)
                if key == ord("h") or key == ord("H"):                        # Cuadro de texto
                    if len(refPt) == 2:
                        self.gestiona_ct (refPt)
                if key == ord("q") or key == ord("Q"):                        # salir
                        break
                self.ver_acciones()

            """
            # Si hay dos puntos de referencia entonces se recorta PARA CLONAR
            if len(refPt) == 2:
            	roi = clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
            	cv2.imshow("ROI", roi)
            	cv2.waitKey(0)
            """
            cv2.destroyAllWindows()
            self.conn.close()
    def tratar_nulos(self,valor):
        if valor is None:
            return 0
        return valor
    def hacerfoto(self,rampa):

        sql = f"select * from parametrizacion where rampa = '{str(rampa)}'"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        fcam1 = None
        for row in resultados:
            idcamara=row['idcamara']
            olx=self.tratar_nulos(row['origen_linea_x'])
            oly=self.tratar_nulos(row['origen_linea_y'])
            tx1x=self.tratar_nulos(row['texto1_x'])
            tx1y=self.tratar_nulos(row['texto1_y'])
            tx2x=self.tratar_nulos(row['texto2_x'])
            tx2y=self.tratar_nulos(row['texto2_y'])
            tx3x=self.tratar_nulos(row['texto3_x'])
            tx3y=self.tratar_nulos(row['texto3_y'])
            tx4x=self.tratar_nulos(row['texto4_x'])
            tx4y=self.tratar_nulos(row['texto4_y'])
            ctx=self.tratar_nulos(row['cuadro_texto_x'])
            cty=self.tratar_nulos(row['cuadro_texto_y'])
            ctw=self.tratar_nulos(row['cuadro_texto_w'])
            cth=self.tratar_nulos(row['cuadro_texto_h'])
        if(len(resultados) > 0):
            sql = "select * from camaras where idcamara = "+str(idcamara)
            self.cursor.execute(sql)
            resultado = self.cursor.fetchone()
            print("Iniciando ....")
            url_camara ="rtsp://"+resultado['usuario']+":"+resultado['passwd']+"@"+resultado['ip']
            cam1 = cv2.VideoCapture(url_camara)
            cam1.set(cv2.CAP_PROP_FRAME_WIDTH,self.wd)
            cam1.set(cv2.CAP_PROP_FRAME_HEIGHT,self.he)
            cam1.set(cv2.CAP_PROP_AUTOFOCUS, 0)
            ret, fcam1 = cam1.read()
            print("Foto tomada...")

            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.rectangle(fcam1, (0, 30), (self.wd, 0), (0,0,0), -1, cv2.LINE_AA)
            cv2.putText(fcam1,"Marque la zona y pulse tecla correcpondiente de accion.",(2,20), font, 0.6,(64,255,0),1,cv2.LINE_AA)
            cv2.rectangle(fcam1, (ctx, cty), (ctx+ctw, cty+cth), (255,255,255), -1, cv2.LINE_AA)
            fcam1 = cv2.line(fcam1,(olx,oly),(olx+80,oly),(0,255,0),2)
            cv2.putText(fcam1,'Linea de texto 1--------------- ',(ctx+10, cty+50), font, 1,(64,255,0),1,cv2.LINE_AA)
            cv2.putText(fcam1,'Linea de texto 2--------------- ',(ctx+10, cty+90), font, 1,(64,255,0),1,cv2.LINE_AA)
            cv2.putText(fcam1,'Linea de texto 3--------------- ',(ctx+10, cty+130), font, 1,(64,255,0),1,cv2.LINE_AA)
            cv2.putText(fcam1,'Linea de texto 4---------------',(ctx+10, cty+180), font, 1,(64,255,0),1,cv2.LINE_AA)




            fcam1=cv2.resize(fcam1,None,fx=0.4, fy=0.4, interpolation = cv2.INTER_CUBIC)



        return(fcam1)

    # Gestiona roi de x y de baliza
    def gestiona_xy(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)

        zona=""
        sql="select * from zonas where seleccion='S' and ras = '"+str(self.rampa)+"' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = f"update zonas set x="+str(x1)+",y="+str(y1)+",w="+str(w)+",h="+str(h)+" where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()

    # Gestiona roi de sensibilidad
    def gestiona_x1y1(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql=f"select * from zonas where seleccion='S' and ras = '{str(self.rampa)}' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi="+str(x1)+",y_roi="+str(y1)+",w_roi="+str(w)+",h_roi="+str(h)+" where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona roi de sensibilidad
    def gestiona_x2y2(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql=f"select * from zonas where seleccion='S' and ras = '{str(self.rampa)}' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi2="+str(x1)+",y_roi2="+str(y1)+",w_roi2="+str(w)+",h_roi2="+str(h)+" where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona roi de sensibilidad
    def gestiona_x3y3(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql=f"select * from zonas where seleccion='S' and ras = '{str(self.rampa)}' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi3="+str(x1)+",y_roi3="+str(y1)+",w_roi3="+str(w)+",h_roi3="+str(h)+" where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona roi de sensibilidad
    def gestiona_x4y4(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql=f"select * from zonas where seleccion='S' and ras = '{str(self.rampa)}' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi4="+str(x1)+",y_roi4="+str(y1)+",w_roi4="+str(w)+",h_roi4="+str(h)+" where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona zonas de lanzamiento
    def gestiona_lanzamiento(self,refPt):

        sql="select * from parametrizacion"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zlanza1=row['zona_lanza1']
            zlanza2=row['zona_lanza2']
            zlanza3=row['zona_lanza3']
            zlanza4=row['zona_lanza4']

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zlanza=str(x1)+','+str(y1)+','+str(w)+','+str(h)
        if zlanza1=="":
            sql = "update parametrizacion set zona_lanza1='"+zlanza+"' where rampa = "+str(self.rampa)
            self.cursor.execute(sql)
            self.conn.commit()
        elif zlanza2=="":
            sql = "update parametrizacion set zona_lanza2='"+zlanza+"' where rampa = "+str(self.rampa)
            self.cursor.execute(sql)
            self.conn.commit()
        elif zlanza3=="":
            sql = "update parametrizacion set zona_lanza3='"+zlanza+"' where rampa = "+str(self.rampa)
            self.cursor.execute(sql)
            self.conn.commit()
        elif zlanza4=="":
            sql = "update parametrizacion set zona_lanza4='"+zlanza+"' where rampa = "+str(self.rampa)
            self.cursor.execute(sql)
            self.conn.commit()

        sql = "insert into control (control) values('RELOAD')"
        self.cursor.execute(sql)
        self.conn.commit()

    def gestiona_x1y1_ext(self,refPt):
        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql="select * from zonas where seleccion='S' and ras = '"+str(self.rampa)+"' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi_ext="+str(x1)+",y_roi_ext="+str(y1)+",w_roi_ext="+str(w)+",h_roi_ext="+str(h)+" where zona='"+str(zona)+"' and ras = '"+str(self.rampa)+"'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona roi de sensibilidad
    def gestiona_x2y2_ext(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql="select * from zonas where seleccion='S' and ras = '"+str(self.rampa)+"' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi2_ext="+str(x1)+",y_roi2_ext="+str(y1)+",w_roi2_ext="+str(w)+",h_roi2_ext="+str(h)+" where zona='"+str(zona)+"' and ras = '"+str(self.rampa)+"'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona roi de sensibilidad
    def gestiona_x3y3_ext(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql="select * from zonas where seleccion='S' and ras = '"+str(self.rampa)+"' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi3_ext="+str(x1)+",y_roi3_ext="+str(y1)+",w_roi3_ext="+str(w)+",h_roi3_ext="+str(h)+" where zona='"+str(zona)+"' and ras = '"+str(self.rampa)+"'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona roi de sensibilidad
    def gestiona_x4y4_ext(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql="select * from zonas where seleccion='S' and ras = '"+str(self.rampa)+"' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
            sql = "update zonas set x_roi4_ext="+str(x1)+",y_roi4_ext="+str(y1)+",w_roi4_ext="+str(w)+",h_roi4_ext="+str(h)+" where zona='"+str(zona)+"' and ras = '"+str(self.rampa)+"'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona zonas de exclusion
    def gestiona_exclusion(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql="select * from zonas where seleccion='S' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']
            exclusion=row['exclusiones']


        if (zona!=""):
            if not exclusion:
                exclusion=str(x1)+','+str(y1)+','+str(w)+','+str(h)
            else:
                exclusion=exclusion+'|'+str(x1)+','+str(y1)+','+str(w)+','+str(h)
            sql = "update zonas set exclusiones='"+exclusion+"' where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()

    # Gestiona configuracion del camino al destino
    def gestiona_camino(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)
        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        cv2.rectangle(self.image, (int(x1*0.4),int(y1*0.4)), (int(x2*0.4),int(y2*0.4)), (255, 255, 255), 2)
        cv2.imshow("Layout Creator", self.image)
        zona=""
        sql="select * from zonas where seleccion='S' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']
            camino=row['camino']


        if (zona!=""):
            if not camino:
                camino=str(x1)+','+str(y1)+','+str(w)+','+str(h)
            else:
                camino=camino+'|'+str(x1)+','+str(y1)+','+str(w)+','+str(h)
            sql = "update zonas set camino='"+camino+"' where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()

    # Gestiona zona donde apareceran textos
    def gestiona_txty(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        zona=""
        sql="select * from zonas where seleccion='S' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            sql = "update zonas set x_textos="+str(x1)+",y_textos="+str(y1)+" where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()
    # Gestiona zona donde aparecera baliza
    def gestiona_bxby(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        zona=""
        sql="select * from zonas where seleccion='S' limit 1"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            sql = "update zonas set x_baliza="+str(x1)+",y_baliza="+str(y1)+" where zona='"+str(zona)+f"' and ras = '{str(self.rampa)}'"
            self.cursor.execute(sql)
            self.conn.commit()
            sql = "insert into control (control) values('RELOAD')"
            self.cursor.execute(sql)
            self.conn.commit()

    # Gestiona Origen de la línea
    def gestiona_orilin(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)

        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        sql = "update parametrizacion set origen_linea_x="+str(x1)+",origen_linea_y="+str(y1)
        self.cursor.execute(sql)
        self.conn.commit()

    # Gestiona cuadro de texto
    def gestiona_ct(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)

        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        sql = "update parametrizacion set cuadro_texto_x="+str(x1)+",cuadro_texto_y="+str(y1)+",cuadro_texto_w="+str(w)+",cuadro_texto_h="+str(h)
        self.cursor.execute(sql)
        self.conn.commit()

    # Gestiona linea de texto 1
    def gestiona_txlin1(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)

        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        sql = "update parametrizacion set texto1_x="+str(x1)+",texto1_y="+str(y1)
        self.cursor.execute(sql)
        self.conn.commit()

    # Gestiona linea de texto 2
    def gestiona_txlin2(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)

        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        sql = "update parametrizacion set texto2_x="+str(x1)+",texto2_y="+str(y1)
        self.cursor.execute(sql)
        self.conn.commit()

    # Gestiona linea de texto 3
    def gestiona_txlin3(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)

        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        sql = "update parametrizacion set texto3_x="+str(x1)+",texto3_y="+str(y1)
        self.cursor.execute(sql)
        self.conn.commit()

    # Gestiona linea de texto 4
    def gestiona_txlin4(self,refPt):

        x1=int(int(refPt[0][0])/0.4)
        y1=int(int(refPt[0][1])/0.4)
        x2=int(int(refPt[1][0])/0.4)
        y2=int(int(refPt[1][1])/0.4)

        x1,x2,y1,y2,w,h=self.calcula_valor(x1,x2,y1,y2)
        sql = "update parametrizacion set texto4_x="+str(x1)+",texto4_y="+str(y1)
        self.cursor.execute(sql)
        self.conn.commit()

    # Gestiona zona donde apareceran textos
    def ver_acciones(self):

        font = cv2.FONT_HERSHEY_SIMPLEX
        zona=""
        sql=f"select * from control where control='LOADZONA' and ras = '{str(self.rampa)}'"
        self.cursor.execute(sql)
        resultados = self.cursor.fetchall()
        for row in resultados:
            zona=row['zona']

        if (zona!=""):
            sql="select * from zonas where zona='"+str(zona)+f"' and ras ='{str(self.rampa)}'"
            self.cursor.execute(sql)
            resultados = self.cursor.fetchall()
            for row in resultados:
                x1=int(row['x']*0.4)
                y1=int(row['y']*0.4)
                x2=x1+int(row['w']*0.4)
                y2=y1+int(row['h']*0.4)
                cv2.rectangle(self.image, (x1, y1), (x2, y2), (0,255,0), 1, cv2.LINE_AA)
                x1=int(row['x_roi']*0.4)
                y1=int(row['y_roi']*0.4)
                x2=x1+int(row['w_roi']*0.4)
                y2=y1+int(row['h_roi']*0.4)
                cv2.rectangle(self.image, (x1, y1), (x2, y2), (0,0,255), 1, cv2.LINE_AA)
                x1=int(row['x_roi2']*0.4)
                y1=int(row['y_roi2']*0.4)
                x2=x1+int(row['w_roi2']*0.4)
                y2=y1+int(row['h_roi2']*0.4)
                cv2.rectangle(self.image, (x1, y1), (x2, y2), (0,0,255), 1, cv2.LINE_AA)
                x1=int(row['x_roi3']*0.4)
                y1=int(row['y_roi3']*0.4)
                x2=x1+int(row['w_roi3']*0.4)
                y2=y1+int(row['h_roi3']*0.4)
                cv2.rectangle(self.image, (x1, y1), (x2, y2), (0,0,255), 1, cv2.LINE_AA)
                x1=int(row['x_roi4']*0.4)
                y1=int(row['y_roi4']*0.4)
                x2=x1+int(row['w_roi4']*0.4)
                y2=y1+int(row['h_roi4']*0.4)
                cv2.rectangle(self.image, (x1, y1), (x2, y2), (0,0,255), 1, cv2.LINE_AA)
                x1=int(row['x_baliza']*0.4)
                y1=int(row['y_baliza']*0.4)
                cv2.putText(self.image,'Zo '+str(row['zona'])+' In '+str(row['mili_seg_togo']),(x1,y1), font, 0.4,(255,204,0),1,cv2.LINE_AA)
                cv2.imshow("Layout Creator", self.image)

            sql = "delete from control where control='LOADZONA'"
            self.cursor.execute(sql)
            self.conn.commit()


    def ver_xy(self,event,x,y,flags,param):

        global refPt, cropping
        if event == cv2.EVENT_LBUTTONDOWN:
            refPt = [(x, y)]
            cropping = True
        elif event == cv2.EVENT_LBUTTONUP:
            refPt.append((x, y))
            cropping = False
            cv2.rectangle(self.image, refPt[0], refPt[1], (255, 255, 255), 2)
            cv2.imshow("Layout Creator", self.image)
        elif event == cv2.EVENT_MOUSEMOVE  and cropping == True:
            cv2.rectangle(self.image, refPt[0], (x,y), (255, 0, 255), -1)
            cv2.imshow("Layout Creator", self.image)

    def calcula_valor(self,v1,v2,v3,v4):

        if v1 <= v2:
            v1f = v1
            v2f = v2
        else:
            v1f = v2
            v2f = v1

        if v3 <= v4:
            v3f = v3
            v4f = v4
        else:
            v3f = v4
            v4f = v3

        wf = v2f-v1f
        hf = v4f-v3f

        return(v1f,v2f,v3f,v4f,wf,hf)
# Callback function to handle button clicks
def clickRampa(rampa):
    roi = Roi(rampa).start()

def abrirCrearCamara(root,cursor):
    #tkinter messagebox
    form_window = tk.Toplevel(root)
    form_window.title("Input Form")

    # Label and entry for Chute ID
    camera_ip_label = tk.Label(form_window, text="Camera IP")
    camera_ip_label.grid(row=0, column=0, padx=10, pady=10)

    camera_ip_entry = tk.Entry(form_window)
    camera_ip_entry.grid(row=0, column=1, padx=10, pady=10)

    camera_user_label = tk.Label(form_window, text="User")
    camera_user_label.grid(row=1, column=0, padx=10, pady=10)

    camera_user_entry = tk.Entry(form_window)
    camera_user_entry.grid(row=1, column=1, padx=10, pady=10)

    camera_pass_label = tk.Label(form_window, text="Password")
    camera_pass_label.grid(row=2, column=0, padx=10, pady=10)

    camera_pass_entry = tk.Entry(form_window)
    camera_pass_entry.grid(row=2, column=1, padx=10, pady=10)


    # Button to submit the form
    submit_button = tk.Button(form_window, text="Submit", command=lambda e=form_window: crearCamara(root,form_window,cursor,camera_ip_entry.get(),camera_user_entry.get(),camera_pass_entry.get()))
    submit_button.grid(row=3, column=0, columnspan=2, pady=10)
def abrirCrearRampa(root,cursor):
    #tkinter messagebox
    form_window = tk.Toplevel(root)
    form_window.title("Input Form")

    # Label and entry for Chute ID
    chute_id_label = tk.Label(form_window, text="Chute ID")
    chute_id_label.grid(row=0, column=0, padx=10, pady=10)

    chute_id_entry = tk.Entry(form_window)
    chute_id_entry.grid(row=0, column=1, padx=10, pady=10)

    # Label and combobox for Camera ID
    camera_id_label = tk.Label(form_window, text="Camera ID")
    camera_id_label.grid(row=1, column=0, padx=10, pady=10)

    camera_id_combobox = ttk.Combobox(form_window)
    sql = "SELECT IDCAMARA,IP FROM CAMARAS"
    cursor.execute(sql)
    results = cursor.fetchall()
    camera_id_combobox['values'] = [f"{result[0]} - {result[1]}" for result in results]
    camera_id_combobox.grid(row=1, column=1, padx=10, pady=10)

    # Button to submit the form
    submit_button = tk.Button(form_window, text="Submit", command=lambda e=form_window: crearRampa(root,form_window,cursor,chute_id_entry.get(),camera_id_combobox.get()))
    submit_button.grid(row=2, column=0, columnspan=2, pady=10)


def abrirBorrarRampa(root,cursor):
    #tkinter messagebox
    form_window = tk.Toplevel(root)
    form_window.title("Delete Chute")

    # Label and combobox for Camera ID
    camera_id_label = tk.Label(form_window, text="Camera ID")
    camera_id_label.grid(row=1, column=0, padx=10, pady=10)

    chute_id_combobox = ttk.Combobox(form_window)
    sql = "SELECT RAMPA FROM PARAMETRIZACION"
    cursor.execute(sql)
    results = cursor.fetchall()
    chute_id_combobox['values'] = [f"Chute - {result[0]}" for result in results]
    chute_id_combobox.grid(row=1, column=1, padx=10, pady=10)

    # Button to submit the form
    submit_button = tk.Button(form_window, text="Submit", command=lambda e=form_window: borrarRampa(root,form_window,cursor,chute_id_combobox.get()))
    submit_button.grid(row=2, column=0, columnspan=2, pady=10)
def borrarRampa(root,form_window,cursor,chute_id):
    form_window.destroy()
    chute_id = chute_id.split(' - ')[1].strip()
    sql = f"DELETE FROM PARAMETRIZACION WHERE RAMPA = '{chute_id}'"
    cursor.execute(sql)
    connection.commit()
    root.destroy()
    InicializarMenu('Chute Configuration')

def crearRampa(root,form_window,cursor,chute_id,camera_id):
    form_window.destroy()
    id_camara = camera_id.split(' - ')[0].strip()
    sql = f"INSERT INTO PARAMETRIZACION (RAMPA,IDCAMARA) VALUES ('{chute_id}','{id_camara}')"
    cursor.execute(sql)
    connection.commit()
    root.destroy()
    InicializarMenu('Chute Configuration')

def crearCamara(root,form_window,cursor,camera_ip,camera_user,camera_pass):
    form_window.destroy()
    sql = f"SELECT MAX(IDCAMARA) FROM CAMARAS"
    cursor.execute(sql)
    res = cursor.fetchone()
    if res is None:
        id_camara = 1
    else:
        id_camara = res[0] + 1
    sql = f"INSERT INTO CAMARAS (IDCAMARA,IP,PUERTO,USUARIO,PASSWD) VALUES ({id_camara},'{camera_ip}','80','{camera_user}','{camera_pass}')"
    cursor.execute(sql)
    connection.commit()
    root.destroy()
    InicializarMenu('Chute Configuration')
# Main application function
def InicializarMenu(titulo='Chute Configuration'):
    # Create the main window
    root = tk.Tk()
    root.title(titulo)
    root.geometry("600x400")  # Set the minimum size of the window

    sql = f"SELECT RAMPA FROM PARAMETRIZACION GROUP BY RAMPA order by rampa asc"
    cursor.execute(sql)
    res = cursor.fetchall()
    elements = [f"{rampa[0]}" for rampa in res]
    if len(elements) < 0:
        tk.messagebox.showinfo("Error", "No chute is configured yet")
    # Create and pack buttons dynamically based on the elements array
    for index, element in enumerate(elements):
        # Calculate row and column for the grid
        row = index // 2
        column = index % 2
        # Create the button with custom styling max width and height   
        
        button = tk.Button(
            root,
            text="Chute "+element,
            command=lambda e=element: clickRampa(e),
            font=("Helvetica", 19),
            bg="lightblue",
            fg="black",
            relief="raised",

            borderwidth=3,
            padx=5,
            pady=2
        )
        button.configure(height=1)
        # Place the button in the grid
        button.grid(row=row, column=column, padx=5, pady=5, sticky="nsew")

    # Configure grid to expand with window resize
    for i in range((len(elements) + 1) // 2):
        root.grid_rowconfigure(i, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.grid_columnconfigure(1, weight=1)

    buttonNuevaRampa = tk.Button(
        root,
        text="New Chute",
        command=lambda: abrirCrearRampa(root,cursor),
        font=("Helvetica", 14),
        bg="lightgreen",
        fg="black",
        relief="raised",
        borderwidth=3,
        padx=10,
        pady=5
    )
    #make it occupy the entire row
    buttonNuevaRampa.grid(row=1, column=0, columnspan=2, padx=10, pady=5, sticky="nsew")
    # Run the application

    buttonBorrarRampa = tk.Button(
        root,
        text="Delete Chute",
        command=lambda: abrirBorrarRampa(root,cursor),
        font=("Helvetica", 14),
        bg="#ec5353",
        fg="black",
        relief="raised",
        borderwidth=3,
        padx=10,
        pady=5
    )
    #make it occupy the entire row
    buttonBorrarRampa.grid(row= 2, column=0, columnspan=2, padx=10, pady=5, sticky="nsew")
    # Run the application

    buttonCrearCamara = tk.Button(
        root,
        text="New Camara",
        command=lambda: abrirCrearCamara(root,cursor),
        font=("Helvetica", 14),
        bg="#13acac",
        fg="black",
        relief="raised",
        borderwidth=3,
        padx=10,
        pady=5
    )
    #make it occupy the entire row
    buttonCrearCamara.grid(row=3, column=0, columnspan=2, padx=10, pady=5, sticky="nsew")
    # Run the application
    root.mainloop()


try:
    jsonConfig = open('config.json')
    cfg = json.load(jsonConfig)
    jsonConfig.close()
except Exception as e:
    aux_function.graba_log('config', 'Error al abrir o parsear el JSON de configuracion')
    sys.exit(1)
try:
    db = cfg['db']
    #connection = cx_Oracle.connect(db['user'], db['passwd'], f"{db['ip']}/{db['schema']}")
    # connection = cx_Oracle.connect("RTPORACLE", "RTPORACLE", "10.200.4.116/m3cogor1")
    connection = psql.connect(db)
    cursor = connection.cursor()
except Exception as e:
    aux_function.graba_log('conexion', 'No se puedo conectar con Oracle # Timeout\n' + str(e))
    sys.exit()
if connection:
    refPt = []
    cropping = False
    
    InicializarMenu('Chute Configuration')