from pyramid.view import view_config
from datetime import datetime, timedelta
from .view_helpers import *


@view_config(route_name='home', renderer='templates/dashboard.jinja2')
@view_config(route_name="json_snapshot", renderer="prettyjson")
def my_view(request):
    return {'project': 'POC Web Interface', 'navgroup': 'dashboard', 'tag_values': get_lastest_tag_values(request), 'card': get_latest_card(request)}


@view_config(route_name='cards', renderer='templates/datelist.jinja2')
@view_config(route_name='json_cards', renderer='prettyjson')
def cards(request):
    return {'datelist': get_all_dates_with_cards(request), 'navgroup': 'cards'}


@view_config(route_name='cards_date', renderer='templates/cardlist.jinja2')
@view_config(route_name='cards_page', renderer='templates/cardlist.jinja2')
@view_config(route_name='json_cards_date', renderer='prettyjson')
@view_config(route_name='json_cards_page', renderer='prettyjson')
def cards_page(request):
    cp = card_page(request)
    cp['datelist'] = get_all_dates_with_cards(request)
    return cp


@view_config(route_name='card_single', renderer='templates/cardsingle.jinja2')
@view_config(route_name='json_card_single', renderer='prettyjson')
def card_single(request):
    card = {}
    try:
        card = list(request.db['cards'].find({"strokeNumber": int(request.matchdict['stroke_number'])}))[0]
    except IndexError:
        pass

    datepage_url = request.referrer.split("/")[3:]
    page_num = 1
    carddate = ""
    if len(datepage_url) > 2:
        page_num = int(datepage_url[2])
    if len(datepage_url) > 1:
        carddate = datepage_url[1]

    return {"card": card, 'navgroup': 'cards', 'datelist': get_all_dates_with_cards(request), 'date': carddate, 'datepage': page_num}


@view_config(route_name='values_all', renderer="templates/valuesall.jinja2")
@view_config(route_name='json_values_all', renderer='prettyjson')
def values_all(request):
    return {'navgroup': 'values', 'current_tag_values': get_lastest_tag_values(request)}


@view_config(route_name="values_tag", renderer="templates/values_single.jinja2")
def values_tag(request):
    tagname = request.matchdict['tagname']
    return {'navgroup': 'values', 'tagname': tagname}


@view_config(route_name="gaugeoff_all", renderer="templates/gaugeoff_all.jinja2")
@view_config(route_name="json_gaugeoff_all", renderer="prettyjson")
def gaugeoff_all(request):
    gaugeoff_list = []
    dateagg = list(request.db['gaugeOff'].aggregate(
        [
            {
                '$project': {
                    'yearMonthDay': {'$dateToString': {'format': "%Y-%m-%d", 'date': "$timestamp"}},
                    'tagname': 1,
                    'dailyTotal': 1,
                    'dailyAverage': 1,
                    'maxDailyValue': 1,
                    'minDailyValue': 1,
                    'currentValue': 1
                }
            },
            {
                '$group': {
                    '_id': "$yearMonthDay",
                    'tags': {'$push': {'name': "$tagname"}},
                    'totals': {'$push': {'total': "$dailyTotal"}},
                    'averages': {'$push': {'average': "$dailyAverage"}},
                    'max': {'$push': {'max': "$maxDailyValue"}},
                    'min': {'$push': {'min': "$minDailyValue"}},
                    'last': {'$push': {'last': "$currentValue"}}
                }
            }
        ]))
    for d in dateagg:
        newGO = {'date': datetime.strptime(d["_id"], '%Y-%m-%d'), 'tags': {}}
        for i in range(0, len(d['tags'])):
            newTagObj = {
                "max": d['max'][i]['max'],
                "min": d['min'][i]['min'],
                "last": d['last'][i]['last'],
                "total": d['totals'][i]['total'],
                "average": d['averages'][i]['average'],
            }
            newGO['tags'][d['tags'][i]['name']] = newTagObj
        gaugeoff_list.append(newGO)
    return {'navgroup': 'gaugeoff', 'data': gaugeoff_list}


@view_config(route_name="fluidshots_all", renderer="templates/fluidshots.jinja2")
@view_config(route_name="json_fluidshots_all", renderer="prettyjson")
def fluidshots_all(request):
    fluidshots = list(request.db['fluidShots'].find())
    return {'navgroup': 'fluidshots', 'data': fluidshots}


@view_config(route_name="welltests_all", renderer="templates/welltests.jinja2")
@view_config(route_name="json_welltests_all", renderer="prettyjson")
def welltests_all(request):
    welltests = list(request.db['wellTests'].find())
    return {'navgroup': 'welltests', 'data': welltests}


@view_config(route_name="runstatus", renderer="templates/runstatus.jinja2")
@view_config(route_name="json_runstatus", renderer="prettyjson")
def welltests_all(request):
    runStatuses = list(request.db['runStatus'].find())
    return {'navgroup': 'runstatus', 'data': runStatuses}
