import datetime
import pprint
import random

import requests


def call_generic(conn, endpoint):
    print("%s \n" % endpoint)
    url = conn + '/%s' % endpoint
    resp = requests.get(url)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0
    data = res['data']
    print('%s \n' % endpoint)
    pprint.pprint(data)
    print('\n')
    return data


def test_get_events(conn):
    call_generic(conn, 'events')


def test_get_rooms(conn):
    call_generic(conn, 'rooms')


def test_get_themes(conn):
    call_generic(conn, 'themes')


def test_book_event(conn):
    url = conn + '/book'
    payload = {
        'id': 'formid',
        'email': 'foo@example.com',
        'datetime': datetime.datetime.now().strftime('%Y-%m-%dT%H:%M'),
        'room': '001',
        'theme': 'A0001',
        'quantity': 1,
    }
    events = call_generic(conn, 'events')
    random.shuffle(events)
    payload['event'] = events[0]['id']
    rooms = call_generic(conn, 'rooms')
    random.shuffle(rooms)
    payload['room'] = rooms[0]['id']
    themes = call_generic(conn, 'themes')
    random.shuffle(themes)
    payload['theme'] = themes[0]['id']
    print("Creating booking with the following payload:\n%s" % payload)
    resp = requests.post(url, json=payload)
    resp.raise_for_status()
    res = resp.json()
    assert res['err'] == 0
    data = res['data']
    pprint.pprint(data)
    print('\n')
