# -*- coding: utf-8 -*-
"""
Created on Wed May 29 15:59:46 2024

@author: 34628
"""




import geopandas as gpd
import pandas as pd
import requests
import json
import re
from shapely.geometry import Polygon
from shapely.geometry import Point

import matplotlib.pyplot as plt


###########################################################################################################
############################# OBTAINING THE SHAPEFILE OF EACH ZIP CODE IN SPAIN ###########################
###########################################################################################################


LISTA=[]
for c in range(1000,53000):
    if c < 10000:
        try:
            c = "0"+str(c)
            print(c)
            
            url="https://apicorp.correos.es/puntos-de-entrega/v1/codigos-postales?codigoPostal=%s&distancia=0"%str(c)
        
            headers={"Ocp-Apim-Subscription-Key": "10d4e4aeab184ccea3aafd55f5bc76bc"}
        
            r=requests.get(url,headers=headers,verify=False)
            j=json.loads(r.text)
            
            for i in range(0,len(j['features'])):
                dic={}
                dic['geometry']=Polygon(j['features'][i]['geometry']['rings'][0])
                dic['codigo']=str(c)
                LISTA.append(dic)
                print("ok")
        except:
            True
    else:
        try:
            print(c)
            
            url="https://apicorp.correos.es/puntos-de-entrega/v1/codigos-postales?codigoPostal=%s&distancia=0"%str(c)
        
            headers={"Ocp-Apim-Subscription-Key": "10d4e4aeab184ccea3aafd55f5bc76bc"}
        
            r=requests.get(url,headers=headers,verify=False)
            j=json.loads(r.text)
            
            for i in range(0,len(j['features'])):
                dic={}
                dic['geometry']=Polygon(j['features'][i]['geometry']['rings'][0])
                dic['codigo']=str(c)
                LISTA.append(dic)
                print("ok")
        except:
            True
        



gdf=gpd.GeoDataFrame(LISTA,geometry='geometry')
gdf.crs = 'epsg:4326'

gdf.to_file('C:/Users/iauciell/Dropbox/zipSpain.gpkg')

gdf.plot()