############################## HU 08 #############################
import rhinoscriptsyntax as rs
import Rhino.Geometry as rg 
import sys, math
import random as rd
sys.path.append("P:\\WWW\\mraontu\\dm2") ### 
import OSM_lib as osm
import DM_lib as dm
###### Rhino Layout Setup
rs.ShowGrid(view="Perspective", show=0)
rs.ShowGridAxes(view="Perspective", show=0)
rs.ViewDisplayMode(view="Perspective", mode="shaded")

rs.EnableRedraw(False)

############################## osm load set up ##############################

OSMpath = "P:\\WWW\\mraontu\\dm2\\OSM\\"  ### path: 
OSMfile = "aldgate.osm"

osm.eAA()  # erase absolutely all objects, even hidden & locked
osm.OSMi(OSMfile, OSMpath, move2Guinea=1)

"""
####  Listen  exportieren (noch fehlerhaft)
OSM_layer = "OSM"  #                              OSM layer
osm_buildings = rs.ObjectsByLayer(OSM_layer)  # alle Gebaeude 

# extrahiere die koordinaten aller Gebaeude
building_coords = [rs.CurvePoints(building) for building in osm_buildings]
building_names = [rs.ObjectName(building) for building in osm_buildings]

# exportiere die koordinaten und namen
export_path = "C:\\Users\\rothl\\dm2\\coords\\"
dm.exportCoordLists(list2export=building_coords, exportedListName='building_coords', path=export_path, fileName='OSM_Buildings')
dm.exportStringList(list2export=building_names, exportedListName='building_names', path=export_path, fileName='OSM_Building_Names')

print("coords fertig exportiert")
"""

############################## Kontur Splitter ##############################

# Parameter
layer_source = "OSM::buildings::_bldg3D_srf"    #  osm layer mit polysrfs
layer_contour = "OSM::buildings::_bldg3D_contour"  # neu layer kontur crvs
contour_step = 3.0                                 # hoehenabstand konturen

if not rs.IsLayer(layer_contour):
    rs.AddLayer(layer_contour, [0, 255, 255]) # new layer kontur


polysurfaces = rs.ObjectsByLayer(layer_source)
for polysrf in polysurfaces:
    brep = rs.coercebrep(polysrf)  # GUID zu Brep 
    bbox = rs.BoundingBox(polysrf)
    
    z_min = bbox[0][2]  # min h
    z_max = bbox[4][2]  # max h
    
    # start/end punkte
    start = rg.Point3d(bbox[0][0], bbox[0][1], z_min) 
    end = rg.Point3d(bbox[0][0], bbox[0][1], z_max)
    # konturen
    contours = rg.Brep.CreateContourCurves(brep, start, end, contour_step)
    # wenn Konturen vorhanden sind, polyline crv
    if contours:
        for contour in contours:
            if isinstance(contour, rg.PolylineCurve):  
                curve_id = rs.AddPolyline([contour.Point(i) for i in range(contour.PointCount)])
            else:  
                curve_id = rs.AddCurve(contour)
            
            if curve_id:
                rs.ObjectLayer(curve_id, layer_contour)

rs.Redraw()
rs.ZoomExtents()
print("HU_08 OSM Umgebung fin ")
