# -*- coding: utf-8 -*-

from django.conf import settings
from django_redis_connector import connector
from pywe_storage import RedisStorage
from pywe_user import get_all_users

from utils.redis.rkeys import SUBSCRIBE_USERINFO_LIST


r1 = connector(settings.REDIS.get('db1', {}))


WECHAT = settings.WECHAT


def fetch_users_func(authorizer_appid, infos):
    print authorizer_appid, infos
    openids = infos.get('data', {}).get('openid', [])
    for openid in openids:
        r1.rpushjson(SUBSCRIBE_USERINFO_LIST % authorizer_appid, {
            'brand_id': authorizer_appid,
            'openid': openid
        })


def fetch_all_users(brand_id):
    wxcfg = WECHAT.get('{}:JSAPI'.format(brand_id), {})

    appid = wxcfg.get('appID')
    secret = wxcfg.get('appsecret')

    get_all_users(appid=appid, secret=secret, storage=RedisStorage(r1), authorizer_appid=brand_id, users_func=fetch_users_func)
