import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

from shapely import wkb


def variable_describe(data):
    if not data or not data.get('stats'):
        return

    stats = dict(data.get('stats'))
    stats.update(data.get('quantiles'))

    return pd.Series(stats)


def dataset_describe(variables):
    describe = dict()

    for variable in variables:
        if variable.describe() is None:
            continue

        describe[variable.column_name] = variable.describe()

    return pd.DataFrame.from_dict(describe)


def head(cls, data):
    from .dataset import Dataset
    from .variable import Variable

    if not data:
        return

    if cls == Variable:
        head = pd.Series(data['head'])
    elif cls == Dataset:
        head = pd.DataFrame(data['glimpses']['head'])

    return head


def tail(cls, data):
    from .dataset import Dataset
    from .variable import Variable

    if not data:
        return

    if cls == Variable:
        tail = pd.Series(data['tail'])
    elif cls == Dataset:
        tail = pd.DataFrame(data['glimpses']['tail'])

    return tail


def counts(data):
    if not data:
        return
    return pd.Series(data['counts'])


def quantiles(data):
    if not data:
        return
    return pd.Series(data['quantiles'])


def top_values(data):
    if not data:
        return

    top_values = pd.DataFrame(data['top_values'])

    position = list(reversed(range(top_values.shape[0])))

    plt.barh(position, top_values['count'], align='center', alpha=0.5)
    plt.yticks(position, top_values['value'])
    plt.xlabel('Count')
    plt.ylabel('Value')
    plt.title('Top values')

    plt.show()


def fields_by_type(data):
    if not data:
        return
    return pd.Series(data['fields_by_type'])


def geom_coverage(geography_id):
    from .geography import Geography
    from ...viz import Map, Layer

    geography = Geography.get(geography_id)
    geom_coverage = wkb.loads(geography.geom_coverage, hex=True)
    geom_coverage_gdf = gpd.GeoDataFrame({'geometry': [geom_coverage]}, geometry='geometry')

    return Map(Layer(geom_coverage_gdf))


def histogram(data):
    return data['histogram']

@@ -2156,33 +2156,517 @@
 a):%0A
+%0A
     r
-eturn data%5B'histogram'%5D
+ange_element = %5Bround(element%5B'min_range'%5D, 2) for element in data%5B'histogram'%5D%5D%0A    count = %5Belement%5B'count'%5D for element in data%5B'histogram'%5D%5D%0A%0A    count_normalized = %5Belement/sum(count) for element in count%5D%0A%0A    position = list(range(len(range_element)))%0A    plt.figure(figsize=(12, 7))%0A    plt.bar(position, count_normalized, align='center', alpha=0.5, width=abs(position%5B1%5D - position%5B0%5D))%0A    plt.xticks(position, range_element)%0A%0A    plt.title('Histogram')%0A    plt.xticks(rotation=60)%0A    plt.show()
 %0A

Add histogram