import json
import geojson
from collections import Counter
import datetime
import bz2

'''

   'ControlledAirspace': 697, 

   'TemporartFlightRestriction': 191, 

   'SpecialUseAirspace': 5, 

   'Emergency': 4, 

   'School': 2, 

   'DenselyPopulatedRegion': 1

 

   Información repetida para TemporartFlightRestriction

   geofence id GEOFENCE-4d054e primera cor = -3.40944444, 42.31583333], [-3.55916667, 42.31638889], [-3.56027778, 42.38305556], [-3.40888889, 42.38333333], [-3.40944444, 42.31583333

   geofence id GEOFENCE-4f5ac1 primera cor = -3.40944444, 42.31583333], [-3.55916667, 42.31638889], [-3.56027778, 42.38305556], [-3.40888889, 42.38333333], [-3.40944444, 42.31583333

 

'''
def export_aeronautics(layer):

    file = "C:/Users/asimarro/Documents/PROJECTS/UTMPlatform/dl-drone-gis/environments/utm/schema/aeronautic/utm-geofences-test.json"

    arr = []

    arrCsv = []

    csvTitle = "id|active|alert_msg|authorized_flightplans|data.address|data.city|data.country|data.description|"
    csvTitle += "geofence_name|data.private|data.propietary_entity|data.responsible.email|data.responsible.other|data.responsible.phone|data.type|"
    csvTitle += "effective_from|effective_until|geofence_id|meta.created_at|meta.last_updated_at|"
    csvTitle += "meta.created_by|meta.last_updated_by|permission_to_fly|manual_authorization"

    
    csv = ""

    ControlledAirspaceJson = []

    geometries = []

    with open(file,  encoding='utf-8-sig') as json_file:

        data = json.load(json_file)
        

        for p in data:

            tipo = p["data"]["type"]

            id = p["geofence_id"]

            geometry = p["geometry_geojson"]


            arr.append(tipo)

            if(tipo==layer): 

                geometry["properties"]["geofence_id"]=id

                csv =  str(p["_id"]["$oid"]) + "|" 

                csv += str(p["active"]) + "|" 
                
                geometry["properties"]['active'] = str(p["active"])

                csv +=  p["alert_msg"] + "|" 

                geometry["properties"]['msg']=p["alert_msg"]

                csv +=  str(len(p["authorized_flightplans"]))+ "|" 

                geometry["properties"]['authorized_flightplans']=p["authorized_flightplans"]

                csv +=  p["data"]["address"]+"|"

                csv +=  p["data"]["city"]+"|"

                csv +=  p["data"]["country"]+"|"

                csv +=  p["data"]["description"]+"|"

                csv +=  p["data"]["name"]+"|"

                geometry["properties"]['name_geofence']=p["data"]["name"]

                csv +=  str(p["data"]["private"])+"|"

                geometry["properties"]['data_prohibition']= str(p["data"]["private"])

                csv +=  p["data"]["proprietary_entity"]+"|"

                csv +=  p["data"]["responsible"]["email"]+"|"

                geometry["properties"]['auth_email']=p["data"]["responsible"]["email"]

                csv +=  p["data"]["responsible"]["other"]+"|"

                csv +=  p["data"]["responsible"]["phone"]+"|"

                geometry["properties"]['auth_phone']= p["data"]["responsible"]["phone"]

                csv +=  p["data"]["type"]+"|"

                
                try:

                    csv +=  str(datetime.datetime.fromtimestamp(p["effective_from"] / 1e3))+"|"

                    geometry["properties"]['timeinit']= str(datetime.datetime.fromtimestamp(p["effective_from"] / 1e3))

                    csv +=  str(datetime.datetime.fromtimestamp(p["effective_until"] / 1e3))+"|"
                    
                    if(p["effective_until"]==3.2535215999E13):
                        geometry["properties"]['timeout']= ""
                    else:
                        geometry["properties"]['timeout']= str(datetime.datetime.fromtimestamp(p["effective_until"] / 1e3))

                except:

                    csv +=  "|"
                    csv +=  "|"

                    geometry["properties"]['timeinit']= ""
                    geometry["properties"]['timeout']= ""

                csv +=  str(p["geofence_id"])+"|"

                try:

                    csv +=  str(datetime.datetime.fromtimestamp(p["metadata"]["created_at"] / 1e3))+"|"

                    geometry["properties"]['created_datetime']=str(datetime.datetime.fromtimestamp(p["metadata"]["created_at"] / 1e3))

                except:

                    csv +=  "|"
                    geometry["properties"]['created_datetime']=""

                try:

                    csv +=  str(datetime.datetime.fromtimestamp(p["metadata"]["last_updated_at"] / 1e3))+"|"

                    geometry["properties"]['updated_datetime']=str(datetime.datetime.fromtimestamp(p["metadata"]["last_updated_at"] / 1e3))

                except:

                    csv +=  "|"
                    geometry["properties"]['updated_datetime']=""
                

                csv +=  p["metadata"]["created_by"]+"|"
                geometry["properties"]['created_by']=p["metadata"]["created_by"]

                csv +=  p["metadata"]["last_updated_by"]+"|"

                csv +=  str(len(p["permissions_to_fly"]))+ "|"

                csv += str(p["manual_authorization"])
                geometry["properties"]['manual_authorization']=str(p["manual_authorization"])

                geometries.append(geometry)

                ControlledAirspaceJson.append(csv)

    

    datosAgrupados = Counter(arr)

    print(datosAgrupados)

    

    with open("C:/Users/asimarro/Documents/PROJECTS/UTMPlatform/dl-drone-gis/environments/utm/schema/aeronautic/"+layer+".csv", 'w') as f:

        f.write(csvTitle + '\n')

        for csvline in ControlledAirspaceJson:

            f.write(csvline + '\n')


    #Returning geometries to include data to DDBB:
    return geometries