from importlib import import_module
from flask import Blueprint, jsonify, request
from sqlalchemy import func, distinct
from inflection import singularize
from app import cache, flask
from app.helpers.cache_helper import api_cache_key

blueprint = Blueprint('api', __name__, url_prefix='/')


@blueprint.route('years/<dataset>/')
@cache.cached(key_prefix=api_cache_key('years_dataset'))
def years(dataset):
    global Model
    Model = get_model(dataset)
    entities = get_columns(['year'])
    query = Model.query.with_entities(*entities).distinct().order_by('year')
    if flask.config['HIDE_DATA']:
        query = query.filter_by(hidden=False)
    query_result = [year[0] for year in query.all()]
    return jsonify(years=query_result)


@blueprint.route('<dataset>/<path:path>/')
@cache.cached(key_prefix=api_cache_key('dataset'))
def api(dataset, path):
    global Model
    Model = get_model(dataset)

    dimensions = [singularize(item) for item in path.split('/')]
    if invalid_dimension(dimensions):
        return 'Error', 403

    filters = {k: v for k, v in request.args.to_dict().items() if k in Model.dimensions()}
    counts = [c for c in [singularize(item) for item in request.args.getlist('count')] if c in Model.dimensions()]

    if flask.config['HIDE_DATA']:
        filters['hidden'] = False
    values = get_values(request)

    group_columns = get_columns(dimensions)
    count_columns = get_columns(counts)
    aggregated_values = [Model.aggregate(v) for v in values]


    headers = get_headers(group_columns) + get_headers(count_columns, '_count') + values
    entities = group_columns + list(map(lambda x: func.count(distinct(x)), count_columns)) + aggregated_values
    query = Model.query.with_entities(*entities).filter_by(**filters).group_by(*group_columns)

    direction = request.args.get('direction', '')
    order = request.args.get('order', None)
    if order:
        if order in Model.dimensions():
            order_by = getattr(Model, order)
        else:
            order_by = Model.aggregate(order)

        if direction.lower() == 'desc':
            order_by = order_by.desc()

        query = query.order_by(order_by)

    limit = request.args.get('limit', None)
    if limit:
        query = query.limit(limit)

    for field, value in get_not_equal_filters(request):
        query = query.filter(getattr(Model, field) != value)

    return jsonify(data=query.all(), headers=headers)

def get_model(dataset):
    class_name = ''.join([x.title() for x in dataset.split('_')])
    Model = getattr(import_module('app.models.' + dataset), class_name)
    return Model

def get_values(request):
    values = [v for v in request.args.getlist('value') if v in Model.values()]
    return values if len(values) else Model.values()

def get_not_equal_filters(request):
    not_filters = [(field[:-1], request.args[field]) for field in request.args.keys() if field.endswith('!')]
    return not_filters

def get_headers(columns, suffix=''):
    return list(map(lambda x: x.key + suffix, columns))


def get_columns(dimensions):
    return [getattr(Model, dimension) for dimension in dimensions]

def invalid_dimension(dimensions):
    return not set(dimensions).issubset(set(Model.dimensions()))

@@ -1534,18 +1534,16 @@
 ues%5D%0D%0A%0D%0A
-%0D%0A
     head
@@ -2495,24 +2495,26 @@
 headers)%0D%0A%0D%0A
+%0D%0A
 def get_mode
@@ -2682,24 +2682,26 @@
 rn Model%0D%0A%0D%0A
+%0D%0A
 def get_valu
@@ -2702,28 +2702,24 @@
 t_values(req
-uest
 ):%0D%0A    valu
@@ -2734,28 +2734,24 @@
 for v in req
-uest
 .args.getlis
@@ -2811,19 +2811,14 @@
  if 
-len(
 values
-)
  els
@@ -2833,24 +2833,26 @@
 values()%0D%0A%0D%0A
+%0D%0A
 def get_not_
@@ -2860,36 +2860,32 @@
 qual_filters(req
-uest
 ):%0D%0A    not_filt
@@ -2903,28 +2903,24 @@
 ld%5B:-1%5D, req
-uest
 .args%5Bfield%5D
@@ -2933,28 +2933,24 @@
 field in req
-uest
 .args.keys()
@@ -2997,24 +2997,26 @@
 _filters%0D%0A%0D%0A
+%0D%0A
 def get_head
@@ -3198,24 +3198,26 @@
 ensions%5D%0D%0A%0D%0A
+%0D%0A
 def invalid_

Change names to not overwrite