import logging
import requests
from flask import Blueprint, jsonify
from requests_oauthlib import OAuth2Session
from hiptweet import celery
from hiptweet.models import HipChatGroup, HipChatRoom
from celery.utils.log import get_task_logger

# set up logging
logger = get_task_logger(__name__)
logger.setLevel(logging.INFO)

# create a Flask blueprint for getting task status info
tasks = Blueprint('tasks', __name__)

@tasks.route('/status/<task_id>')
def status(task_id):
    result = celery.AsyncResult(task_id)
    return jsonify({"status": result.state})


def paginated_get(url, session=None, **kwargs):
    """
    Return a generator of results for this API call, based on the structure
    of HipChat's API return values.
    """
    session = session or requests.Session()
    payload = {
        "start-index": 0,
        "max-results": 1000,
    }
    payload.update(kwargs)
    while url:
        resp = session.get(url, params=payload)
        resp.raise_for_status()
        result = resp.json()
        for item in result["items"]:
            yield item
        url = result.get("links", {}).get("next", "")


@celery.task
def fetch_room_names(group_id):
    group = HipChatGroup.query.get(group_id)
    capabilities_url = group.install_info[0].capabilities_url
    capabilities_resp = requests.get(capabilities_url)
    capabilities_resp.raise_for_status()
    base_api_url = (
        capabilities_resp.json()["capabilities"]["hipchatApiProvider"]["url"]
    )
    session = OAuth2Session(token=group.twitter_oauth.token)
    rooms_info = paginated_get(base_api_url + "room", session=session)
    for room_info in rooms_info:
        room_id = room_info['id']
        room = HipChatRoom.query.get(room_id)
        if not room:
            room = HipChatRoom(id=room_id, group=group)
        room.name = room_info["name"]
        db.session.add(room)
    db.session.commit()

@@ -530,15 +530,23 @@
 fy(%7B
+%0A        
 %22stat
-us
+e
 %22: r
@@ -556,16 +556,51 @@
 lt.state
+,%0A        %22info%22: result.info,%0A    
 %7D)%0A%0A%0Adef
@@ -632,16 +632,31 @@
 on=None,
+ callback=None,
  **kwarg
@@ -998,16 +998,74 @@
 ayload)%0A
+        if callable(callback):%0A            callback(resp)%0A
         
@@ -1245,16 +1245,27 @@
 ery.task
+(bind=True)
 %0Adef fet
@@ -1278,16 +1278,22 @@
 m_names(
+self, 
 group_id
@@ -1603,16 +1603,59 @@
 %5D%0A    )%0A
+    rooms_info_url = base_api_url + %22room%22%0A
     sess
@@ -1711,77 +1711,291 @@
 en)%0A
-    rooms_info = paginated_get(base_api_url + %22room%22, session=session
+%0A    def update_state(resp):%0A        if not resp.ok:%0A            return%0A        start_index = resp.json()%5B%22startIndex%22%5D%0A        self.update_state(state=%22STARTED%22, meta=%7B%22startIndex%22: start_index%7D)%0A%0A    rooms_info = paginated_get(rooms_info_url, session=session, callback=update_state
 )%0A  

Make fetch_room_names report progress