from datasette import hookimpl
from datasette.utils import detect_spatialite
from shapely import wkt


def get_spatial_tables(conn):
    if not detect_spatialite(conn):
        return {}
    spatial_tables = {}

    c = conn.cursor()
    c.execute(
        """SELECT f_table_name, f_geometry_column, srid, spatial_index_enabled
                 FROM geometry_columns"""
    )
    for row in c.fetchall():
        if row[3] != 1:
            print(
                "Column {column} in table {table} has no spatial index; datasette-geo will ignore it.".format(
                    column=row[1], table=row[0]
                )
            )
            continue
        spatial_tables[row[0]] = row[1]
    return spatial_tables


def get_bounds(conn, spatial_tables):
    c = conn.cursor()
    res = {}
    for table, column in spatial_tables.items():
        c.execute(
            "SELECT AsText(Envelope(GUnion({column}))) FROM {table}".format(
                table=table, column=column
            )
        )
        data = c.fetchone()[0]
        if data is None:
            continue

        bbox = wkt.loads(data)
        res[table] = bbox.bounds
    return res

[((7, 11, 7, 34), 'datasette.utils.detect_spatialite', 'detect_spatialite', ({(7, 29, 7, 33): 'conn'}, {}), '(conn)', False, 'from datasette.utils import detect_spatialite\n'), ((41, 15, 41, 30), 'shapely.wkt.loads', 'wkt.loads', ({(41, 25, 41, 29): 'data'}, {}), '(data)', False, 'from shapely import wkt\n')]