import requests
from pprint import pprint
from starlette.applications import Starlette
from starlette.requests import Request
from starlette.responses import RedirectResponse
from starlette.routing import Route

# if using Heroku, change this to https://YOURAPP.herokuapp.com
SERVER_URL = "https://woon-study-2.herokuapp.com"

ROOM_NAME = 'test'

# whatever URL parameter uniquely identifies the participant
# oTree calls it participant_label,
# but other platforms may require it to be called something else like 'id' or 'pid',
# so you can customize that here.
PARTICIPANT_LABEL_PARAM = 'participant_label'

# required if you set OTREE_AUTH_LEVEL
OTREE_REST_KEY = ''


GET = requests.get
POST = requests.post


def call_api(method, *path_parts, **params) -> dict:
    print('params is', params)
    path_parts = '/'.join(path_parts)
    print('path_parts is',path_parts)
    url = f'{SERVER_URL}/api/{path_parts}/'
    print('url is',url)
    resp = method(url, json=params, headers={'otree-rest-key': OTREE_REST_KEY})
    print('resp is',resp)
    if not resp.ok:
        msg = (
            f'Request to "{url}" failed '
            f'with status code {resp.status_code}: {resp.text}'
        )
        raise Exception(msg)
    return resp.json()

def root(request: Request):
    print('reqest.query_params is', request.query_params) #is this not working?
    params = dict(request.query_params)
    print('params in root is', params)
    # participant_label =  params.pop(PARTICIPANT_LABEL_PARAM)
    participant_label =  'testlabel'


    call_api(
        POST,
        'participant_vars',
        room_name=ROOM_NAME,
        participant_label=participant_label,
        # vars=dict(workerId='test1',hitId='test2',assignmentId='test3'),
        vars=params,

    )

    room_url = f'{SERVER_URL}/room/{ROOM_NAME}/?participant_label={participant_label}' 
    print('room_url is', room_url)
    return RedirectResponse(room_url)


app = Starlette(debug=True, routes=[Route('/', root)])

