import json, requests

try:
    from urllib.parse import urlencode
except ImportError:
    from urllib import urlencode

h_domain = 'hypothes.is'
url = 'http://jonudell.net/h/lorem.html'
user = 'hypothesistest'
query_url_template = 'https://%s/api/search?{query}' % h_domain

all = 6
tagged_latin = 2
tagged_latin_and_vocabulary = 1

base_params = { 'uri': url }
user_params = { 'uri': url, 'user': 'hypothesistest' }

params = {
    'base_params': base_params,
    'user_params': user_params
    }

def search(params):
    h_url = query_url_template.format(query=urlencode(params, True))
    json = requests.get(h_url).json()
    return h_url, json

def count_results(params_name, params_dict, expected_name, expected_count):
    (query_url, result) = search(params_dict)
    count = len(result['rows'])
    msg = 'test: %s, expected %d, got %d (%s)\n query: %s\n' % (expected_name, expected_count, count, params_name, query_url)
    try:
      assert count == expected_count
      print 'OK! ' + msg
    except:
      print 'FAIL! ' + msg

if __name__ == "__main__":

    print 'test url: %s\ntest user: %s\nbase_params: %s\nuser_params %s\n\n' % (url, user, base_params, user_params)

    for params_name in ['base_params', 'user_params']:

        current_params = params[params_name]
        count_results(params_name, current_params, 'all', all)

        current_params = params[params_name]
        current_params['tags'] = 'latin'
        count_results(params_name, current_params, 'tagged_latin', tagged_latin)

        current_params = params[params_name]
        current_params['tags'] =  tuple(['latin', 'vocabulary'])
        count_results(params_name, current_params, 'tagged_latin_and_vocabulary', tagged_latin_and_vocabulary)

test url: http://jonudell.net/h/lorem.html
test user: hypothesistest
base_params: {'uri': 'http://jonudell.net/h/lorem.html'}
user_params {'uri': 'http://jonudell.net/h/lorem.html', 'user': 'hypothesistest'}


OK! test: all, expected 6, got 6 (base_params)
 query: https://hypothes.is/api/search?uri=http%3A%2F%2Fjonudell.net%2Fh%2Florem.html

OK! test: tagged_latin, expected 2, got 2 (base_params)
 query: https://hypothes.is/api/search?uri=http%3A%2F%2Fjonudell.net%2Fh%2Florem.html&tags=latin

FAIL! test: tagged_latin_and_vocabulary, expected 1, got 2 (base_params)
 query: https://hypothes.is/api/search?uri=http%3A%2F%2Fjonudell.net%2Fh%2Florem.html&tags=latin&tags=vocabulary

OK! test: all, expected 6, got 6 (user_params)
 query: https://hypothes.is/api/search?uri=http%3A%2F%2Fjonudell.net%2Fh%2Florem.html&user=hypothesistest

FAIL! test: tagged_latin, expected 2, got 6 (user_params)
 query: https://hypothes.is/api/search?tags=latin&uri=http%3A%2F%2Fjonudell.net%2Fh%2Florem.html&user=hypothesistest

FAIL! test: tagged_latin_and_vocabulary, expected 1, got 6 (user_params)
 query: https://hypothes.is/api/search?tags=latin&tags=vocabulary&uri=http%3A%2F%2Fjonudell.net%2Fh%2Florem.html&user=hypothesistest