import json
import operator
import pendulum
import requests
import bottle
import logging
import sys
from bottle import Jinja2Template, jinja2_view, static_file, response, Bottle, request
import functools
from cheroot import wsgi
import os
import sh

logger = logging.Logger('scriptie')

Jinja2Template.settings = {'autoescape': True}
view = functools.partial(jinja2_view, template_lookup=["templates"])

app = Bottle()
app.config['TEMPLATES_AUTO_RELOAD'] = True

@app.hook('after_request')
def enable_cors():
    """
    You need to add some headers to each request.
    Don't use the wildcard '*' for Access-Control-Allow-Origin in production.
    """
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'PUT, GET, POST, DELETE, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'

@app.route('/')
@view('index.html')
def times():
    users = [{"name": "Sam", "token": "MTNmN2Y0ZmJhYjU1YTA0ZDQzMjRjMzQ5ZjljYmM2MTY6YXBpX3Rva2Vu", "url": "https://toggl.com/reports/api/v3/workspace/2840459/summary/time_entries", "project_id": 160017805},
             {"name": "Robin", "token": "NTRjZGNjNTBiMWUwOTg4M2M4OWU2NTQ4MTM1MjliMjM6YXBpX3Rva2Vu", "url": "https://toggl.com/reports/api/v3/workspace/3227035/summary/time_entries", "project_id": 158375002},
             {"name": "Maxim", "token": "YTk4OTVmYzM0OGYyMzViY2I3Y2NkZjIyOTdiY2E1NjQ6YXBpX3Rva2Vu", "url": "https://toggl.com/reports/api/v3/workspace/4225096/summary/time_entries", "project_id": 160231315},
             {"name": "Wilco", "token": "NDM5YjAwMzQzOGQ2ZDk0NTc5OTI0MTA3ZDljODRkYzA6YXBpX3Rva2Vu", "url": "https://toggl.com/reports/api/v3/workspace/4233969/summary/time_entries", "project_id": 160298868}]

    today = pendulum.now()
    start_date = today.start_of('week').to_date_string()
    end_date   = today.end_of('week').to_date_string()

    for user in users:
        headers = {"Authorization": "Basic " + user['token'], "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:76.0) Gecko/20100101 Firefox/76.0", "Origin": "https://toggl.com"}
        params = {"start_date": start_date, "end_date": end_date, "grouping": "projects", "sub_grouping": "time_entries", "include_time_entry_ids": False}
        groups = requests.post(user['url'], headers=headers, json=params).json()['groups']
        total_secs = 0
        for group in groups:
            if group['id'] == user['project_id']:
                for task in group['sub_groups']:
                    total_secs += task['seconds']

        mins, secs = divmod(total_secs, 60)
        hrs, mins = divmod(mins, 60)
        user['time'] = f"{hrs:02}:{mins:02}:{secs:02}"
        user['secs'] = total_secs


    output_data = [(user['name'], user['time'], user['secs']) for user in users]
    output_data.sort(key=operator.itemgetter(2), reverse=True)

    return {'user_data': output_data}

@app.route('/static/:path#.+#', name='static')
def static(path):
    return static_file(path, root='static')
