import uuid
from datetime import datetime
from pytz import timezone

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


RECRAWL_QUEUE_PATH = "/user/{user_id}/hosts/{host_id}/recrawl/queue/".format(user_id=USER_ID, host_id=HOST_ID)
RECRAWL_QUOTA_PATH = "/user/{user_id}/hosts/{host_id}/recrawl/quota/".format(user_id=USER_ID, host_id=HOST_ID)


def get_quota():
    r = SESSION.get(API_URL + RECRAWL_QUOTA_PATH)
    c = validate_api_response(r, ['daily_quota', 'quota_remainder'])

    return {
        'daily_quota': c['daily_quota'],
        'quota_remainder': c['quota_remainder']
    }


def get_tasks(date_from=None, date_to=None, limit=100):
    r = SESSION.get(API_URL + RECRAWL_QUEUE_PATH, params={
        'date_from': date_from,
        'date_to': date_to,
        'limit': limit
    })
    c = validate_api_response(r, ['tasks'])

    return c['tasks']


def get_task(task_id):
    r = SESSION.get(API_URL + RECRAWL_QUEUE_PATH + task_id)
    c = validate_api_response(r, ['task_id', 'url', 'added_time', 'state'])

    return c


def create_task(url):
    r = SESSION.post(API_URL + RECRAWL_QUEUE_PATH, json={'url': url})
    c = validate_api_response(r, ['task_id'])

    return c['task_id']


def run(create_new_task=False):
    quota = get_quota()
    print 'Recrawl quota: ' + str(quota)

    tasks = get_tasks()
    print 'Current recrawl tasks: \n' + json.dumps(tasks, indent=2)

    task_not_found_id = "c7fe80c0-36e3-11e6-8b2d-df96aa592c0a"
    print "Testing getting non existing task: " + task_not_found_id
    try:
        get_task(task_not_found_id)
        raise RuntimeError("Should not happen")
    except HTTPError:
        print "Ok, task not found"
        pass

    if not create_new_task:
        return

    date_from = datetime.now(timezone('UTC')).isoformat()
    random_url = HOST + '/' + str(uuid.uuid4())
    print "Adding new task: " + random_url
    task_id = create_task(random_url)
    date_to = datetime.now(timezone('UTC')).isoformat()

    print "Testing adding already existing URL..."
    is_error = False
    try:
        task_id = create_task(random_url)
    except:
        is_error = True

    if not is_error:
        raise Exception("Fail")
    else:
        print "Ok, API returned error"

    print "Getting new task: " + task_id
    t1 = get_task(task_id)
    print json.dumps(t1, indent=2)

    print "Testing getting tasks for date range..."
    l = get_tasks(date_from, date_to, 1)
    assert len(l) == 1
    t2 = l[0]
    assert task_id == t2['task_id']
    print "Ok"


if __name__ == "__main__":
    run(True)