from pyramid.view import view_config
from .view_helpers import *
from bson import json_util


# JSON
@view_config(route_name="json_lastcard", renderer="prettyjson")
def json_lastcard(request):
    return get_latest_card(request)


@view_config(route_name="json_valuesbetween", renderer="prettyjson")
@view_config(route_name="json_valuesbetween_wparams", renderer="prettyjson")
def json_valuesbetween(request):
    end = datetime.now()
    try:  # Attempt to get a value from the request.
        end = request.matchdict['enddt']
        end = end.replace("T", " ")
        end = datetime.strptime(end, "%Y-%m-%d %H:%M:%S.%fZ")
    except KeyError:
        pass

    start = end - timedelta(days=2)
    try:  # Attempt to get a value from the request.
        start = request.matchdict['startdt']
        start = start.replace("T", " ")
        start = datetime.strptime(start, "%Y-%m-%d %H:%M:%S.%fZ")
    except KeyError:
        pass

    tag_data = []
    grouped_tags = request.db['wellData'].aggregate([
        {
            '$match': {"timestamp": {"$gt": start, "$lte": end}}
        },
        {
            '$sort': {"tagname": 1, "timestamp": 1}
        },
        {
            '$group': {
                '_id': "$tagname",
                'timestamps': {'$push': "$timestamp"},
                'currentValues': {'$push': "$currentValue"}
            }
        }
    ])

    for t in grouped_tags:
        tag_data.append({"tagname": t['_id'], "timestamps": list(map(lambda a: a.strftime("%Y-%m-%d %H:%M:%S.%fZ"), t['timestamps'])), "currentValues": t['currentValues']})
    return {'values': tag_data, 'start': start, 'end': end}


@view_config(route_name="json_valuesdaterange", renderer="prettyjson")
def json_valuesdaterange(request):
    date_limits = list(request.db['wellData'].aggregate([
        {"$group": {
            "_id": 'null',
            "last": {"$max": "$timestamp"},
            "first": {"$min": "$timestamp"}
        }}
    ]))[0]
    return {'first_date': date_limits['first'], 'last_date': date_limits['last']}


@view_config(route_name="json_singlevaluebetween", renderer="prettyjson")
@view_config(route_name="json_singlevaluebetween_wparams", renderer="prettyjson")
def json_singlevaluebetween(request):
    end = datetime.now()
    try:  # Attempt to get a value from the request.
        end = request.matchdict['enddt']
        end = end.replace("T", " ")
        end = datetime.strptime(end, "%Y-%m-%d %H:%M:%S.%fZ")
    except KeyError:
        pass

    start = end - timedelta(days=7)
    try:  # Attempt to get a value from the request.
        start = request.matchdict['startdt']
        start = start.replace("T", " ")
        start = datetime.strptime(start, "%Y-%m-%d %H:%M:%S.%fZ")
    except KeyError:
        pass

    tag_data = []
    grouped_tags = request.db['wellData'].aggregate([
        {"$match": {"tagname": request.matchdict['tagname'], 'timestamp': {'$gt': start, '$lte': end}}},
        {
            '$sort': {"timestamp": 1}
        }
    ])
    return {'values': list(grouped_tags), 'start': start, 'end': end}


@view_config(route_name="json_singlevaluedaterange", renderer="prettyjson")
def json_singlevaluedaterange(request):
    date_limits = list(request.db['wellData'].aggregate([
        {"$match": {"tagname": request.matchdict['tagname']}},
        {"$group": {
            "_id": 'null',
            "last": {"$max": "$timestamp"},
            "first": {"$min": "$timestamp"}
        }}
    ]))[0]
    return {'first_date': date_limits['first'], 'last_date': date_limits['last']}


@view_config(route_name="json_runstatusnow", renderer="prettyjson")
def json_runstatusnow(request):
    status = False
    try:
        status = list(request.db['runStatus'].find().sort("timestamp", -1).limit(1))[0]
    except IndexError:
        pass

    return {'runstatus': status}
