# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""

from apps.home import blueprint
from flask import render_template, request
from flask_login import login_required
from jinja2 import TemplateNotFound

from apps.home.modules.utils import *
from apps.home.modules.mountainbikel import *

@blueprint.route('/index')
#@login_required
def index():
    # return render_template('home/index.html', segment='index')
    if is_running_in_docker():
        sys.stderr.write("Running in a Docker container\n")
        csv_file = '/root/HealthData/garmin_bike.csv'
    else:
        sys.stderr.write("NOT Running in a Docker container\n" + os.getcwd() + "\n")
        csv_file = './HealthData/garmin_bike.csv'
    return render_template(
        'home/mountainbikel_index.html',
        segment='index',
        **homepage_data(csv_file),
        mosum=json.dumps(
            monthly_sum_barchart_concurrent2(csv_file, 'elevationGain', 1,
                                             'Höhenmeter pro Monat', '(m)', 'Jahr', 'Jahr'),
            cls=plotly.utils.PlotlyJSONEncoder),  # ** überführt die dict-Werte in named arguments
        distsum=json.dumps(
            monthly_sum_barchart_concurrent2(csv_file, 'distance', 1,
                                             'Entfernung pro Monat', '(km)', 'Jahr', 'Jahr'),
            cls=plotly.utils.PlotlyJSONEncoder),  # ** überführt die dict-Werte in named arguments
        timesum=json.dumps(
            monthly_sum_barchart_concurrent2(csv_file, 'movingDuration', 1,
                                             'Stunden pro Monat', '(h)', 'Jahr', 'Jahr'),
            cls=plotly.utils.PlotlyJSONEncoder),  # ** überführt die dict-Werte in named arguments
    )

@blueprint.route('/<template>')
@login_required
def route_template(template):

    try:

        if not template.endswith('.html'):
            template += '.html'

        # Detect the current page
        segment = get_segment(request)

        # Serve the file (if exists) from app/templates/home/FILE.html
        return render_template("home/" + template, segment=segment)

    except TemplateNotFound:
        return render_template('home/page-404.html'), 404

    except:
        return render_template('home/page-500.html'), 500


# Helper - Extract current page name from request
def get_segment(request):

    try:

        segment = request.path.split('/')[-1]

        if segment == '':
            segment = 'index'

        return segment

    except:
        return None
