#from pgConnection import PgConnection
from B01Common import CommonSql

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

    def executeQuery(self):
        country_id = self.getAdminRegionIdLevel(34,0)
        '''
        # First step look for the id for the country level in spain
        query = "SELECT * FROM administrative_region_levels where country_id = 34 and hierarchy_level = 0"
        try:
            self._cursor.execute(query)
            result = self._cursor.fetchall()
            if len(result) == 1:
                country_id = result[0][0]
            else:
                raise Exception("No country level found")

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

        # look for the country geometry
        query = "SELECT ST_AsEWKT(geom) as geom, 'nationalCode'  FROM spain.country"
        try:
            self._cursor.execute(query)
            result = self._cursor.fetchall()
            if len(result) == 1:
                country_geom = result[0][0]
                natcode = result[0][1]
            else:
                raise Exception("No country geometry found")

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


        # insert the geometry in database (el primer parametro de la query está de relleno, lo metemos xq no nos deja meter un null)
        # parent_id, natcode, name, geom,region_level_id
        self.insertIntoAdministrativeRegion(country_id, natcode, 'Spain', country_geom,country_id)
        
        #query = '''INSERT INTO administrative_regions (parent_id, name, geom,administrative_region_levels_region_level_id)
        #        VALUES
        #        ('{parent}', '{name}',ST_GeomFromText('{geom}'),'{country_id}') ;'''.format(parent=country_id,name='Spain',geom=country_geom,country_id=country_id)
        #
        #self._cursor.execute(query)
        #self._pgconn.connection.commit()
        #count = self._cursor.rowcount
        #print (count, "Records inserted successfully into the table")




''' basic test to get an uuid from postgres
data = "select uuid_generate_v4();"
cursor.execute(data)
uid = cursor.fetchall()
for row in uid:
    print(row[0])
'''

'''
data = "INSERT INTO administrative_region (parent_id, name, geom) VALUES (1, 'Sunday') ;"




data = "SET search_path TO spain ; SELECT * FROM ccaa ;"

cursor.execute(data)

CCAA = cursor.fetchall()



for row in CCAA:
       print("natcode = ", row[5], )
       print("nameunit = ", row[6])
       print("codnut1  = ", row[7], "\n")
       data2 = "INSERT INTO administrative_region (day_number, day_name) VALUES (1, 'Sunday') ;"


'''
