#!/usr/bin/env python
import sys
import click
import json
from time import time, sleep
from inbox import APIClient
from inbox.client.util import generate_id
import sys

TIMEOUT = 120


class TimeoutError(Exception):
    pass


def self_send(client, email):
    draft = client.drafts.create(to=[{'name': 'Inbox SelfSend',
                                      'email': email}],
                                 subject=generate_id())
    draft.send()

    start = time()
    while time() - start < TIMEOUT:
        th = client.threads.where(tag='sent', subject=draft.subject).first()
        if th:
            return th
        sleep(0.1)
    raise TimeoutError('self-send')


def self_receive(client, thread):
    start = time()
    while time() - start < TIMEOUT:
        for th in client.threads.where(subject=thread.subject):
            if 'inbox' in [t['name'] for t in th.tags]:
                return th
        sleep(0.1)
    raise TimeoutError('self-recv')


def remove(client, thread):
    thread.archive()

    start = time()
    while time() - start < TIMEOUT:
        if not len(client.threads.where(tag='inbox',
                                        subject=thread.subject).all()):
            return
        sleep(0.1)
    raise TimeoutError('archive')


def do_run(email, access_token):
    client = APIClient(access_token=access_token)
    stats = {'email': email}

    start = time()
    client.contacts.where(limit=100).all()
    stats['contacts'] = time() - start

    start = time()
    client.threads.where(limit=100).all()

    stats['threads'] = time() - start

    start = time()
    th = self_send(client, email)
    stats['send'] = time() - start

    start = time()
    th = self_receive(client, th)
    stats['recv'] = time() - start

    start = time()
    remove(client, th)
    stats['trash'] = time() - start
    return stats


@click.command()
@click.option('--email', default=None, help='Email address')
@click.option('--access_token', default=None, help='Access token')
def main(email, access_token):
    try:
        stats = do_run(email, access_token)
        print json.dumps(stats)
    except TimeoutError as e:
        print json.dumps({'email': email,
                          'message': "Timed out.",
                          'event': str(e)})
        sys.exit(2)


if __name__ == '__main__':
        main()

@@ -150,16 +150,63 @@
 rate_id%0A
+from inbox.client.errors import APIClientError%0A
 import s
@@ -223,16 +223,39 @@
 T = 120%0A
+current_operation = %22%22%0A
 %0A%0Aclass 
@@ -1365,24 +1365,53 @@
 ess_token):%0A
+    global current_operation%0A
     client =
@@ -1478,16 +1478,51 @@
 email%7D%0A%0A
+    current_operation = 'contacts'%0A
     star
@@ -1585,26 +1585,33 @@
   stats%5B
-'contacts'
+current_operation
 %5D = time
@@ -1614,32 +1614,66 @@
 time() - start%0A%0A
+    current_operation = 'threads'%0A
     start = time
@@ -1717,17 +1717,16 @@
 ).all()%0A
-%0A
     stat
@@ -1727,25 +1727,33 @@
   stats%5B
-'threads'
+current_operation
 %5D = time
@@ -1756,32 +1756,63 @@
 time() - start%0A%0A
+    current_operation = 'send'%0A
     start = time
@@ -1858,22 +1858,33 @@
   stats%5B
-'send'
+current_operation
 %5D = time
@@ -1887,32 +1887,63 @@
 time() - start%0A%0A
+    current_operation = 'recv'%0A
     start = time
@@ -1989,22 +1989,33 @@
   stats%5B
-'recv'
+current_operation
 %5D = time
@@ -2022,24 +2022,56 @@
 () - start%0A%0A
+    current_operation = 'trash'%0A
     start = 
@@ -2110,23 +2110,33 @@
   stats%5B
-'trash'
+current_operation
 %5D = time
@@ -2613,16 +2613,262 @@
 exit(2)%0A
+    except APIClientError as e:%0A        msg = %22Error during: %7B%7D%22.format(current_operation)%0A        print json.dumps(%7B'email': email,%0A                          'message': msg,%0A                          'event': e.as_dict()%7D)%0A        sys.exit(2)%0A%0A%0A
 %0A%0Aif __n

Add json output on errors.