import os
from B01Common import CommonSql
from E01CommonVolumes import CommonVolumes

class Duplication(CommonSql):
    def __init__(self,pgconn):
        CommonSql.__init__(self,pgconn)

    def check_duplication(self, tables_f):
        print('table: ', tables_f)
        geometries=[]
        for table in tables_f:
            query_layer='''SELECT layer_id FROM layers_volume WHERE name='{}'; '''.format(table)
            try: 
                self._cursor.execute(query_layer)
                l=self._cursor.fetchall()
                layer=l[0][0]
            except Exception as ex :
                print("ERROR: ", type(ex), ex.args)

            cm=CommonVolumes(self._pgconn)

            query1='''SELECT vol_id, geom_buffer FROM airspace_volume WHERE layers_layer_id='{}' '''.format(layer)

            try:
                self._cursor.execute(query1)
                geometries_results=self._cursor.fetchall()
                geometries= geometries + geometries_results
                
            except Exception as ex :
                print("ERROR: ", type(ex), ex.args)
        
        #evaluate similarity:
        while len(geometries)>0:
            geometry_eval0=geometries[0][1]
            geometry_eval0_id=geometries[0][0]
            if geometry_eval0_id=='cda5fe4a-4dd5-4978-8932-b4fae4b3e60b':
                pass

            geometries.pop(0)
            geoms_remove=[]

            for other_geoms in geometries:
                geometry_eval1=other_geoms[1] 
                geometry_eval1_id=other_geoms[0]
                   
                query2='''SELECT ST_AREA(ST_INTERSECTION('{}','{}')), ST_AREA('{}'), ST_AREA('{}') '''.format(geometry_eval0,geometry_eval1, geometry_eval0,geometry_eval1)
                try:
                    self._cursor.execute(query2)
                    intersection=self._cursor.fetchall()
                    is_similarA= intersection[0][0]/intersection[0][1]
                    is_similarB= intersection[0][0]/intersection[0][2]
                    if is_similarA >= 0.98 or is_similarB>=0.98:
                        print(geometry_eval0_id, geometry_eval1_id)
                        #delete geometry
                        if is_similarB ==1:
                            cm.delete_geom(geometry_eval1_id)
                            geoms_remove.append(other_geoms)
                        elif is_similarA ==1:
                            cm.delete_geom(geometry_eval0_id)
                            break
                        else:
                            cm.delete_geom(geometry_eval1_id)
                            geoms_remove.append(other_geoms)       
                    
                except Exception as ex :
                    print("ERROR: ", type(ex), ex.args)

            for g in geoms_remove:
                geometries.remove(g)
            

