# coding: utf-8
import json
import geojson
from geojson import Feature, Point, FeatureCollection, Polygon
import os


def parse_geojson(fname):
    print fname
    with open(fname, 'r') as f:
        fc = geojson.load(f)

    fc.keys()

    fc['type']

    newgj = FeatureCollection([])

    id_feat = str(fc).count('"id":')-1

    def fix_props(props, z):
        props['height'] = z
        props['base_height'] = 0
        props['level'] = 1
        if not 'name' in props:
            props['name'] =''

        if 'fill' in props:
            props['color'] = props['fill']
        elif 'stroke' in props:
            props['color'] = 'white'

        return props

    for f in fc.features:
        if f.geometry.type == 'GeometryCollection':
            for p in f.geometry.geometries:
                newprops = fix_props(f.properties, p['coordinates'][0][0][2])
                newfeat = {"type": "Feature",
                           'id': id_feat,
                           'properties': newprops,
                           'geometry': p}
                newgj.features.append(newfeat)
                id_feat += 1

        else:
            f.properties = fix_props(
                f.properties, f.geometry['coordinates'][0][0][2])
            newgj.features.append(f)

    with open('new/' + fname, 'w') as outfile:
        json.dump(newgj, outfile)


def main():
    for fname in [f for f in os.listdir('./') if 'geojson' in f and ('dismesso' in f or 'obsoleto' in f)]:
        parse_geojson(fname)

if __name__ == '__main__':
    main()