# Path: gbdxtools/vector_layers.py
# class VectorGeojsonLayer(VectorLayer):
#     """ Represents a vector layer created from a geojson source
# 
#         Args:
#             geojson (dict): a list of geojson features to render
#             styles (list): A list of style objects to be applied to the layer
#     """
#     def __init__(self, geojson, **kwargs):
#         super(VectorGeojsonLayer, self).__init__(**kwargs)
#         self.geojson = geojson
# 
#     def _datasource_def(self):
#         return {'type': 'geojson', 'data': self.geojson}
# 
#     def _layer_def(self, style):
#         return {
#             'id': type(style).__name__, # TODO - make this unique in the various styles
#             'type': style.type,
#             'source': self.source_id,
#             'paint': style.paint()
#         }
# 
# class VectorTileLayer(VectorLayer):
#     """ Represents a vector tile layer in a tile map
# 
#         Args:
#             url (str): a vector tile url template
#             source_name (str): the name of the source layer in the vector tiles
#             styles (list): A list of style objects to be applied to the layer
#     """
#     def __init__(self, url=None, source_layer_name='GBDX_Task_Output', **kwargs):
#         super(VectorTileLayer, self).__init__(**kwargs)
#         self.url = url
#         self.source_layer_name = source_layer_name
# 
#     def _datasource_def(self):
#         return {'type': 'vector', 'tiles': [self.url]}
# 
#     def _layer_def(self, style):
#         return {
#             'id': type(style).__name__, # TODO - make this unique in the various styles
#             'type': style.type,
#             'source': self.source_id,
#             'source-layer':  self.source_layer_name,
#             'paint': style.paint()
#         }
# 
# class ImageLayer(object):
#     """ A layer for rendering images and image arrays to slippy maps
# 
#         Args:
#             image (str): a vector tile url template
#             coordinates: the coordinate bounds (list of polygon corners) for placing the image
# 
#         Returns:
#             An string of the layer definition
#     """
#     def __new__(self, image, coordinates):
#         return json.dumps({
#             "id": uuid.uuid4().hex,
#             "type": "raster",
#             "source": {
#                 "type": "image",
#                 "url": image,
#                 "coordinates": coordinates
#             }
#         })
# 
# Path: gbdxtools/auth.py
# def Auth(**kwargs):
#     global auth
#     if auth is None or len(kwargs) > 0:
#         auth = _Auth(**kwargs)
#     return auth


from string import Template
from imageio import imsave
from io import BytesIO
from shapely.wkt import loads as load_wkt
from collections import OrderedDict
from shapely.ops import cascaded_union
from shapely.geometry import shape, box, mapping
from gbdxtools.vector_layers import VectorGeojsonLayer, VectorTileLayer, \
                                    ImageLayer
from gbdxtools.map_templates import BaseTemplate
from gbdxtools.auth import Auth
            from IPython.display import display
            from IPython.display import display
import base64
import dask.array as da
import requests
import json, time, os
        r.raise_for_status()

        return r.json(object_pairs_hook=OrderedDict)['aggregations']

    def tilemap(self, query, styles={}, bbox=[-180,-90,180,90], zoom=16, 
                      api_key=os.environ.get('MAPBOX_API_KEY', None), 
                      image=None, image_bounds=None,
                      index="vector-user-provided", name="GBDX_Task_Output", **kwargs):
        """
          Renders a mapbox gl map from a vector service query
        """
        try:
        except:
            print("IPython is required to produce maps.")
            return

        assert api_key is not None, "No Mapbox API Key found. You can either pass in a token or set the MAPBOX_API_KEY environment variable."

        wkt = box(*bbox).wkt
        features = self.query(wkt, query, index=index)

        union = cascaded_union([shape(f['geometry']) for f in features])
        lon, lat = union.centroid.coords[0]
        url = 'https://vector.geobigdata.io/insight-vector/api/mvt/{z}/{x}/{y}?';
        url += 'q={}&index={}'.format(query, index);

        if styles is not None and not isinstance(styles, list):
            styles = [styles]

        map_id = "map_{}".format(str(int(time.time())))

# Path: gbdxtools/vector_layers.py
# class VectorGeojsonLayer(VectorLayer):
#     """ Represents a vector layer created from a geojson source
# 
#         Args:
#             geojson (dict): a list of geojson features to render
#             styles (list): A list of style objects to be applied to the layer
#     """
#     def __init__(self, geojson, **kwargs):
#         super(VectorGeojsonLayer, self).__init__(**kwargs)
#         self.geojson = geojson
# 
#     def _datasource_def(self):
#         return {'type': 'geojson', 'data': self.geojson}
# 
#     def _layer_def(self, style):
#         return {
#             'id': type(style).__name__, # TODO - make this unique in the various styles
#             'type': style.type,
#             'source': self.source_id,
#             'paint': style.paint()
#         }
# 
# class VectorTileLayer(VectorLayer):
#     """ Represents a vector tile layer in a tile map
# 
#         Args:
#             url (str): a vector tile url template
#             source_name (str): the name of the source layer in the vector tiles
#             styles (list): A list of style objects to be applied to the layer
#     """
#     def __init__(self, url=None, source_layer_name='GBDX_Task_Output', **kwargs):
#         super(VectorTileLayer, self).__init__(**kwargs)
#         self.url = url
#         self.source_layer_name = source_layer_name
# 
#     def _datasource_def(self):
#         return {'type': 'vector', 'tiles': [self.url]}
# 
#     def _layer_def(self, style):
#         return {
#             'id': type(style).__name__, # TODO - make this unique in the various styles
#             'type': style.type,
#             'source': self.source_id,
#             'source-layer':  self.source_layer_name,
#             'paint': style.paint()
#         }
# 
# class ImageLayer(object):
#     """ A layer for rendering images and image arrays to slippy maps
# 
#         Args:
#             image (str): a vector tile url template
#             coordinates: the coordinate bounds (list of polygon corners) for placing the image
# 
#         Returns:
#             An string of the layer definition
#     """
#     def __new__(self, image, coordinates):
#         return json.dumps({
#             "id": uuid.uuid4().hex,
#             "type": "raster",
#             "source": {
#                 "type": "image",
#                 "url": image,
#                 "coordinates": coordinates
#             }
#         })
# 
# Path: gbdxtools/auth.py
# def Auth(**kwargs):
#     global auth
#     if auth is None or len(kwargs) > 0:
#         auth = _Auth(**kwargs)
#     return auth


# Path: gbdxtools/vectors.py
from string import Template
from imageio import imsave
from io import BytesIO
from shapely.wkt import loads as load_wkt
from collections import OrderedDict
from shapely.ops import cascaded_union
from shapely.geometry import shape, box, mapping
from gbdxtools.vector_layers import VectorGeojsonLayer, VectorTileLayer, \
                                    ImageLayer
from gbdxtools.map_templates import BaseTemplate
from gbdxtools.auth import Auth
            from IPython.display import display
            from IPython.display import display
import base64
import dask.array as da
import requests
import json, time, os

        r.raise_for_status()

        return r.json(object_pairs_hook=OrderedDict)['aggregations']

    def tilemap(self, query, styles={}, bbox=[-180,-90,180,90], zoom=16, 
                      api_key=os.environ.get('MAPBOX_API_KEY', None), 
                      image=None, image_bounds=None,
                      index="vector-user-provided", name="GBDX_Task_Output", **kwargs):
        """
          Renders a mapbox gl map from a vector service query
        """
        try:
        except:
            print("IPython is required to produce maps.")
            return

        assert api_key is not None, "No Mapbox API Key found. You can either pass in a token or set the MAPBOX_API_KEY environment variable."

        wkt = box(*bbox).wkt
        features = self.query(wkt, query, index=index)

        union = cascaded_union([shape(f['geometry']) for f in features])
        lon, lat = union.centroid.coords[0]
        url = 'https://vector.geobigdata.io/insight-vector/api/mvt/{z}/{x}/{y}?';
        url += 'q={}&index={}'.format(query, index);

        if styles is not None and not isinstance(styles, list):
            styles = [styles]

        map_id = "map_{}".format(str(int(time.time())))

        map_data = VectorTileLayer(url, source_name=name, styles=styles, **kwargs)