from ctypes import c_void_p, cast

import shapely.geometry
from shapely.geometry.base import BaseGeometry
from shapely.geos          import lgeos


def buildGeometryCollection(geoms):
   # Validate that each of the given geometry objects is not null. Without this, we will get a
   # crash in GEOS for trying to use a NULL pointer.
   usable_geoms = []
   for cur_geom in geoms:
      if cur_geom._geom is not None and not cur_geom.is_empty:
         usable_geoms.append(cur_geom)

   # Create a Shapely GeometryCollection using clones of the given geometry objects. We have to
   # create a clone so that the collection owns the backing GEOS objects.
   num_geoms = len(usable_geoms)
   subs = (c_void_p * num_geoms)()
   for i, geom in enumerate(usable_geoms):
      geom_clone = lgeos.GEOSGeom_clone(geom._geom)
      subs[i] = cast(geom_clone, c_void_p)

   collection = shapely.geometry.GeometryCollection()
   # 7 is GEOS_GEOMETRYCOLLECTION
   collection._geom = lgeos.GEOSGeom_createCollection(7, subs, num_geoms)

   return collection
