from base import *

USER_ID = get_user_id()
print "API user id: " + str(USER_ID)

HOST = 'https://khaliullin.info'
HOST_ID = url_to_host_id(HOST)
print "Using host: " + HOST_ID

INDEXING_HISTORY_PATH = "/user/{user_id}/hosts/{host_id}/indexing/history/".format(user_id=USER_ID, host_id=HOST_ID)
INDEXING_SAMPLES_PATH = "/user/{user_id}/hosts/{host_id}/indexing/samples/".format(user_id=USER_ID, host_id=HOST_ID)


def get_indexing_history(date_from=None, date_to=None):
    r = SESSION.get(API_URL + INDEXING_HISTORY_PATH, params={
        'date_from': date_from,
        'date_to': date_to,
    })
    c = validate_api_response(r, ['indicators'])

    return c['indicators']


def get_indexing_samples(offset=0, limit=100):
    r = SESSION.get(API_URL + INDEXING_SAMPLES_PATH, params={
        'offset': offset,
        'limit': limit
    })
    c = validate_api_response(r, ['count', 'samples'])

    return c


def run():
    print "Getting indexing history: "
    all_history = get_indexing_history()
    print_json(all_history)

    print "Testing getting indexing history for date range..."
    all_history_slice = all_history['HTTP_2XX'][1:-2]
    date_from = all_history_slice[0]['date']
    date_to = all_history_slice[-1]['date']
    date_range_history = get_indexing_history(date_from=date_from, date_to=date_to)
    assert date_range_history['HTTP_2XX'] == all_history_slice
    print "Ok"

    total_samples = 15
    print "Getting first " + str(total_samples) + " indexing samples:"

    all_samples = get_indexing_samples(limit=total_samples)['samples']
    print_json(all_samples)

    print "Testing indexing samples paging..."
    page_size = 5
    for offset in range(0, total_samples, page_size):
        page_samples = get_indexing_samples(offset=offset, limit=page_size)['samples']
        for idx, page_sample in enumerate(page_samples):
            ref_sample = all_samples[offset + idx]
            assert ref_sample == page_sample

    print "Ok"


if __name__ == "__main__":
    run()
