#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import codecs
import csv

'''
Clase  que serializa una clase en python a partir de la página
https://wiki.openstreetmap.org/wiki/Map_Features
Se ha copiado la tabla de dicha página en un excel. Y se ha pasado
a un csv. Ese csv es el fichero orginal.
'''

featureTypes = ['aerialway','aeroway','amenity','barrier','boundary','building','craft','emergency',
'geological','highway','cycleway','historic','landuse','leisure','man_made','military','natural','office','place', 'power',
'public_transport','railway','route','shop','sport','telecom','tourism','waterway','ana']

class CreateOsmFeaturesPythonClass:
    def __init__(self):
        self._curPath = os.path.dirname(os.path.abspath(os.path.realpath(__file__)))
    
    # esta función solo se llama una vez
    def buildCsv(self):
        csvFile = os.path.join(self._curPath, 'csv/Libro1.csv')
        csvFileResult = os.path.join(self._curPath, 'csv/LibroPrueba.csv')
        counter = 0
        counterfeature=0
        typeosm=[]
        with codecs.open(csvFile, 'r', encoding='utf-8',
                 errors='ignore') as fp:
        #with open(csvFile) as fp:
            for line in fp:
                lineArray = line.split(';')
                if int(len(lineArray[0]))>0 and int(len(lineArray[1]))>0:
                    counter += 1
                    if lineArray[0] == featureTypes[counterfeature]:
                        typeosm.append([lineArray[0],lineArray[1],lineArray[2],lineArray[3]])
                        
                        #print('"{}", "{}": "{}", "{}"'.format(str(counter).zfill(3),str(counterfeature).zfill(3), lineArray[0],lineArray[1]))

                    elif lineArray[0] == featureTypes[counterfeature+1]:
                        #print('"{}", "{}"'.format(lineArray[0], featureTypes[counterfeature+1]))
                        counterfeature = counterfeature +1
                        typeosm.append([lineArray[0],lineArray[1],lineArray[2],lineArray[3]])
                        #print('"{}", "{}": "{}", "{}"'.format(str(counter).zfill(3),str(counterfeature).zfill(3), lineArray[0],lineArray[1]))
                    else:
                        pass
                            
            with open(csvFileResult, 'w', newline='') as csvfile:
                fieldname= ['id','primary','secundary','type','description']
                count=0
                writer = csv.DictWriter(csvfile, fieldnames=fieldname)
                writer.writeheader()
                for linea in typeosm:
                   writer.writerow({'id':count, 'primary':linea[0], 'secundary':linea[1], 'type':linea[2], 'description':linea[3]})
                   count= count+1

cr = CreateOsmFeaturesPythonClass()
cr.buildCsv()