from bottle import Bottle, response, request
import sys
import requests
from toggl.api_client import TogglClientApi
import base64

credentials = {'token': '13f7f4fbab55a04d4324c349f9cbc616', 'user_agent': 'kijken mensen hier echt naar? wild.', 'workspace_id': '2840459'}

client = TogglClientApi(credentials)

app = Bottle()

auth_headers = {'Authorization': 'Basic %s' % base64.b64encode(credentials['token'].encode('utf-8') + b":api_token").decode('utf-8')}

@app.route('/start/<name>', method='PUT')
def start_timer(name):
    workspace_id = credentials['workspace_id']
    projects = requests.get(f"https://api.track.toggl.com/api/v9/workspaces/{workspace_id}/projects", headers=auth_headers).json()
    project_id: int
    for project in projects:
        if (project['name'].startswith(name)):
            project_id = project['id']
            break
    else:
        response.status = 400
        return 'Invalid project name'

    start_msg = {'time_entry': {'description': '', 'pid': project_id, 'created_with': 'kakrokei', 'tags': []}}

    res = requests.post("https://api.track.toggl.com/api/v8/time_entries/start", headers=auth_headers, json=start_msg)
    response.status = res.status_code
    return res.text


@app.route('/stop', method='PUT')
def stop_timer():
    running_id = requests.get("https://api.track.toggl.com/api/v8/time_entries/current", headers=auth_headers).json()['data']['id']

    res = requests.put(f"https://api.track.toggl.com/api/v8/time_entries/{running_id}/stop", headers=auth_headers)
    response.status = res.status_code
    return res.text
