from B01Common import CommonSql
from E01CommonVolumes import CommonVolumes
from B02ExpAeronautics import export_aeronautics
import datetime
from shapely.geometry import Polygon
import os

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

    def CreateAeronauticsVolumes(self):

        cm= CommonVolumes(self._pgconn)
        name_layers=['ControlledAirspace','ControlledAirspace', 'TemporartFlightRestriction', 'SpecialUseAirspace', 'Emergency', 'schools_volume', 'DenselyPopulatedRegion']

        for name in name_layers:
            #create layer:
            layer_id=cm.get_layerid(name)
            
            if layer_id==None:
                #creation of layer if not exists
                layer_id=cm.create_layer(name,3)
                print('register for layer created')
            else:
                cm.delete_geofencelayer(name)

            #we execute de exportation from json:
            if name=='schools_volume':
                data= export_aeronautics('School')  
            else:
                data= export_aeronautics(name)   

            
            
            #we insert volumes into data base:
            for geom in data:
                #buffer properties:
                buffer=0
                lowerLimit=geom['properties']['altitude_constrain'][0]
                upperLimit=geom['properties']['altitude_constrain'][1]
                active = geom['properties']['active']
                country='ESP'
                prohibition=geom['properties']['data_prohibition']
                region=1
                geometry=self.convert_geom(geom['geometry']['type'],geom['geometry']['coordinates'])
                name_feature=geom['properties']['geofence_id']
                feature_id= 0
                #authority and notification to
                email_auth=''
                phone_auth=''
                if(geom['properties']['auth_email']!="Mail Responsable"):
                    email_auth=geom['properties']['auth_email']
                if(geom['properties']['auth_phone'].isdigit()):
                    phone_auth=geom['properties']['auth_phone']
                authority_id=cm.authority(name='',service='',contact_name='',site_url='',email=email_auth,phone=phone_auth)
                notification_id=cm.authority(name='',service='',contact_name='',site_url='',email=email_auth,phone=phone_auth)
                #time periods
                if(geom['properties']['timeout']==""):
                    period_type_id=1
                    time_period_time_period_id=[]
                else:
                    period_type_id=2
                    time_period_time_period_id2=cm.specification_time(geom['properties']['timeinit'],geom['properties']['timeout'],[],[])
                    time_period_time_period_id=[time_period_time_period_id2]
                #metadata 
                creationdate=geom['properties']['created_datetime']
                lastupdate=geom['properties']['updated_datetime']
                author=geom['properties']['created_by']
                metadata_metadata_id=cm.specification_metadata(creationdate,lastupdate,author)
                #restrictions
                code_zone=1
                code_uspace=[2]
                code_zone_reason=[1]
                volume_limitation_def=[1,4,7]
                upperlimitnorestriccion=0

                code_restriction=[]
                condition_expression=[]
                if(geom['properties']['manual_authorization']=='True'):
                    code_restriction=[2] 
                if(geom['properties']['authorized_flightplans']!=[]):
                    code_restriction=[2,3] 
                    condition_expression.append(4)
                if(geom['properties']['authorized_flightplans']==[] and geom['properties']['manual_authorization']!='True'):
                    code_restriction=[1]

                message=geom['properties']['msg']
                identifier=""
                intervalbefore=""
                
                v= cm.insertIntoVolumes(name_feature,lowerLimit,upperLimit,geometry, buffer,
                layer_id,feature_id,message,author, country, code_zone, code_restriction,
                code_uspace,code_zone_reason,prohibition,region,authority_id,notification_id,metadata_metadata_id,time_period_time_period_id,
                volume_limitation_def,condition_expression,upperlimitnorestriccion,period_type_id, identifier, intervalbefore, active)
                print(v)

                if v[0]==False :
                    print("The insertion of the entity through to an exception, its properties would be deleted on the ddbb")
                    if len(v)>2 : 
                        cm.delete_geom(v[1])
                    elif(len(v)>1):
                        for time_id in time_period_time_period_id:
                            query_delete_time=""" DELETE FROM slot_time WHERE time_period_time_period_id='{}';
                                            DELETE FROM time_period WHERE time_period_id='{}';""".format(time_id, time_id)
                            try:
                                self._cursor.execute(query_delete_time)
                                self._pgconn.connection.commit()

                            except Exception as ex :
                                print("ERROR: ", type(ex), ex.args)
                        
                        
                        query_delete= """DELETE FROM metadata WHERE metada_id='{}';
                                        DELETE FROM authority WHERE authority_oid='{}';
                                        DELETE FROM authority WHERE authority_oid='{}';
                                    """.format(metadata_metadata_id,authority_id,notification_id)
                        try:
                            self._cursor.execute(query_delete)
                            self._pgconn.connection.commit()

                        except Exception as ex :
                            print("ERROR: ", type(ex), ex.args)

        
    
        

    def convert_geom(self, geom_type, coordinates):
        if geom_type == 'Polygon':
            geom_text = Polygon(coordinates[0]) 
            
        elif geom_type == 'MultiPolygon':
            i=0
            for x in coordinates:
                if i==0:
                    geom_text=Polygon(x)
                i=i+1
        else:
            print('ERROR')
            #think about how to do this exception
       
        return geom_text
       
