# Path: spillway/collections.py
# class Feature(AbstractFeature):
#     """GeoJSON Feature dict."""
# 
#     def __init__(self, id=None, geometry=None, properties=None,
#                  crs=None, iterable=(), **kwargs):
#         super(Feature, self).__init__()
#         self['type'] = self.__class__.__name__
#         self['geometry'] = geometry or {}
#         self['properties'] = properties or kwargs or {}
#         if id:
#             self['id'] = id
#         if crs:
#             self['crs'] = NamedCRS(crs)
#         self.update(iterable)
# 
#     @property
#     def geojson(self):
#         if not self.is_serialized('geometry'):
#             return self._dumps()
#         geom = self['geometry'] or '{}'
#         keys = six.viewkeys(self) - {'geometry'}
#         props = json.dumps({k: self[k] for k in keys}, cls=JSONEncoder)[1:-1]
#         return '{"geometry": %s, %s}' % (str(geom), props)
# 
# class FeatureCollection(AbstractFeature):
#     """GeoJSON FeatureCollection dict."""
# 
#     def __init__(self, features=None, crs=None, iterable=(), **kwargs):
#         super(FeatureCollection, self).__init__()
#         self['type'] = self.__class__.__name__
#         if crs:
#             self['crs'] = NamedCRS(crs)
#         if features and not isinstance(next(iter(features)), Feature):
#             self['features'] = [Feature(**feat) for feat in features]
#         else:
#             self['features'] = features or []
#         self.update(iterable, **kwargs)
# 
#     @property
#     def geojson(self):
#         if not self.has_serialized_geom:
#             return self._dumps()
#         features = ','.join(map(str, self['features']))
#         keys = six.viewkeys(self) - {'features'}
#         collection = '%s, "features": [' % json.dumps(
#             {k: self[k] for k in keys}, cls=JSONEncoder)[:-1]
#         return ''.join([collection, features, ']}'])
# 
#     @property
#     def has_serialized_geom(self):
#         return any(feat.is_serialized('geometry') for feat in self['features'])
# 
# class LayerCollection(AbstractFeature):
#     """Layer dict of FeatureCollections."""
# 
#     def __init__(self, iterable=(), **kwargs):
#         super(LayerCollection, self).__init__()
#         self.update(iterable, **kwargs)
#         for key, val in six.viewitems(self):
#             if not isinstance(val, FeatureCollection):
#                 self[key] = FeatureCollection(**val)
# 
#     @property
#     def geojson(self):
#         layers = ','.join(['"%s": %s' % (k, v.geojson)
#                            for k, v in six.viewitems(self)])
#         return '{%s}' % layers
# 
# class LinkedCRS(dict):
#     def __init__(self, srid=4326, iterable=(), **kwargs):
#         self['type'] = 'link'
#         if isinstance(srid, int):
#             self['properties'] = {
#                 'href': 'http://spatialreference.org/ref/epsg/%s/proj4/' % srid,
#                 'type': 'proj4'
#             }
#         else:
#             iterable = iterable or srid
#         self.update(iterable, **kwargs)
# 
# class NamedCRS(dict):
#     def __init__(self, srid=4326, iterable=(), **kwargs):
#         self['type'] = 'name'
#         if isinstance(srid, int):
#             self['properties'] = {'name': 'urn:ogc:def:crs:EPSG::%s' % srid}
#         else:
#             iterable = iterable or srid
#         self.update(iterable, **kwargs)
# 
# def as_feature(data):
#     """Returns a Feature or FeatureCollection.
# 
#     Arguments:
#     data -- Sequence or Mapping of Feature-like or FeatureCollection-like data
#     """
#     if not isinstance(data, (Feature, FeatureCollection)):
#         if is_featurelike(data):
#             data = Feature(**data)
#         elif has_features(data):
#             data = FeatureCollection(**data)
#         elif isinstance(data, collections.Sequence):
#             data = FeatureCollection(features=data)
#         elif has_layer(data):
#             data = LayerCollection(data)
#         elif has_coordinates(data):
#             data = Feature(geometry=data)
#         elif isinstance(data, collections.Mapping) and not data:
#             data = Feature()
#     return data


import datetime
from django.test import SimpleTestCase
from spillway.collections import (Feature, FeatureCollection, LayerCollection,
    LinkedCRS, NamedCRS, as_feature)
    def test_empty_crs(self):
        crs = {'type': 'name',
               'properties': {'name': 'urn:ogc:def:crs:EPSG::4326'}}
        self.assertEqual(NamedCRS(), crs)

    def test_iterable(self):
        iterable = (('geometry', self.geom),)
        self.assertEqual(Feature(iterable=iterable),
                         {'geometry': self.geom, 'type': 'Feature', 'properties': {}})

    def test_str(self):
        feat = Feature(properties={'event': datetime.date(1899, 1, 1)})
        self.assertIn('"properties": {"event": "1899-01-01"}', str(feat))


class LayerCollectionTestCase(SimpleTestCase):
    def setUp(self):
        # Instantiate using a plain dict as we want to test for conversion to a
        # layer FeatureCollection below.
        self.lc = LayerCollection({'layer': dict(**FeatureCollection())})

    def test_has_featurecollection(self):
        self.assertIsInstance(self.lc['layer'], FeatureCollection)

    def test_geojson(self):
        self.assertIn('{"layer":', self.lc.geojson)

    def test_as_feature(self):
        self.assertIsInstance(as_feature(dict(self.lc['layer'])),
                              FeatureCollection)

# Path: spillway/collections.py
# class Feature(AbstractFeature):
#     """GeoJSON Feature dict."""
# 
#     def __init__(self, id=None, geometry=None, properties=None,
#                  crs=None, iterable=(), **kwargs):
#         super(Feature, self).__init__()
#         self['type'] = self.__class__.__name__
#         self['geometry'] = geometry or {}
#         self['properties'] = properties or kwargs or {}
#         if id:
#             self['id'] = id
#         if crs:
#             self['crs'] = NamedCRS(crs)
#         self.update(iterable)
# 
#     @property
#     def geojson(self):
#         if not self.is_serialized('geometry'):
#             return self._dumps()
#         geom = self['geometry'] or '{}'
#         keys = six.viewkeys(self) - {'geometry'}
#         props = json.dumps({k: self[k] for k in keys}, cls=JSONEncoder)[1:-1]
#         return '{"geometry": %s, %s}' % (str(geom), props)
# 
# class FeatureCollection(AbstractFeature):
#     """GeoJSON FeatureCollection dict."""
# 
#     def __init__(self, features=None, crs=None, iterable=(), **kwargs):
#         super(FeatureCollection, self).__init__()
#         self['type'] = self.__class__.__name__
#         if crs:
#             self['crs'] = NamedCRS(crs)
#         if features and not isinstance(next(iter(features)), Feature):
#             self['features'] = [Feature(**feat) for feat in features]
#         else:
#             self['features'] = features or []
#         self.update(iterable, **kwargs)
# 
#     @property
#     def geojson(self):
#         if not self.has_serialized_geom:
#             return self._dumps()
#         features = ','.join(map(str, self['features']))
#         keys = six.viewkeys(self) - {'features'}
#         collection = '%s, "features": [' % json.dumps(
#             {k: self[k] for k in keys}, cls=JSONEncoder)[:-1]
#         return ''.join([collection, features, ']}'])
# 
#     @property
#     def has_serialized_geom(self):
#         return any(feat.is_serialized('geometry') for feat in self['features'])
# 
# class LayerCollection(AbstractFeature):
#     """Layer dict of FeatureCollections."""
# 
#     def __init__(self, iterable=(), **kwargs):
#         super(LayerCollection, self).__init__()
#         self.update(iterable, **kwargs)
#         for key, val in six.viewitems(self):
#             if not isinstance(val, FeatureCollection):
#                 self[key] = FeatureCollection(**val)
# 
#     @property
#     def geojson(self):
#         layers = ','.join(['"%s": %s' % (k, v.geojson)
#                            for k, v in six.viewitems(self)])
#         return '{%s}' % layers
# 
# class LinkedCRS(dict):
#     def __init__(self, srid=4326, iterable=(), **kwargs):
#         self['type'] = 'link'
#         if isinstance(srid, int):
#             self['properties'] = {
#                 'href': 'http://spatialreference.org/ref/epsg/%s/proj4/' % srid,
#                 'type': 'proj4'
#             }
#         else:
#             iterable = iterable or srid
#         self.update(iterable, **kwargs)
# 
# class NamedCRS(dict):
#     def __init__(self, srid=4326, iterable=(), **kwargs):
#         self['type'] = 'name'
#         if isinstance(srid, int):
#             self['properties'] = {'name': 'urn:ogc:def:crs:EPSG::%s' % srid}
#         else:
#             iterable = iterable or srid
#         self.update(iterable, **kwargs)
# 
# def as_feature(data):
#     """Returns a Feature or FeatureCollection.
# 
#     Arguments:
#     data -- Sequence or Mapping of Feature-like or FeatureCollection-like data
#     """
#     if not isinstance(data, (Feature, FeatureCollection)):
#         if is_featurelike(data):
#             data = Feature(**data)
#         elif has_features(data):
#             data = FeatureCollection(**data)
#         elif isinstance(data, collections.Sequence):
#             data = FeatureCollection(features=data)
#         elif has_layer(data):
#             data = LayerCollection(data)
#         elif has_coordinates(data):
#             data = Feature(geometry=data)
#         elif isinstance(data, collections.Mapping) and not data:
#             data = Feature()
#     return data


# Path: tests/test_collections.py
import datetime
from django.test import SimpleTestCase
from spillway.collections import (Feature, FeatureCollection, LayerCollection,
    LinkedCRS, NamedCRS, as_feature)

    def test_empty_crs(self):
        crs = {'type': 'name',
               'properties': {'name': 'urn:ogc:def:crs:EPSG::4326'}}
        self.assertEqual(NamedCRS(), crs)

    def test_iterable(self):
        iterable = (('geometry', self.geom),)
        self.assertEqual(Feature(iterable=iterable),
                         {'geometry': self.geom, 'type': 'Feature', 'properties': {}})

    def test_str(self):
        feat = Feature(properties={'event': datetime.date(1899, 1, 1)})
        self.assertIn('"properties": {"event": "1899-01-01"}', str(feat))


class LayerCollectionTestCase(SimpleTestCase):
    def setUp(self):
        # Instantiate using a plain dict as we want to test for conversion to a
        # layer FeatureCollection below.
        self.lc = LayerCollection({'layer': dict(**FeatureCollection())})

    def test_has_featurecollection(self):
        self.assertIsInstance(self.lc['layer'], FeatureCollection)

    def test_geojson(self):
        self.assertIn('{"layer":', self.lc.geojson)

    def test_as_feature(self):
        self.assertIsInstance(as_feature(dict(self.lc['layer'])),
                              FeatureCollection)

        self.assertIsInstance(as_feature(dict(self.lc)), LayerCollection)