#!/usr/bin/env python
# coding=utf-8
import json
from django.core.management import BaseCommand

from rpc.cache import unread_cache


class Command(BaseCommand):
    """
        处理 未读数目统计 存储问题
    """

    def handle(self, *args, **options):
        # 已经缓存了的私信未读总数的用户们
        user_keys = unread_cache.keys(u'converstaion:*')
        for user_key in user_keys:
            user_id = user_key.split(u':')[2]
            user_key = user_key[7:]  # 去掉unread的前缀
            # 找出该用户所有私信未读消息
            user_cs = unread_cache.hgetall(user_key)
            print u'handle user_id is {}, user_key is {}, cs_unread is {}'.format(
                user_id, user_key, json.dumps(user_cs)
            )
            # 依次逐个重新赋值
            new_key = u'conversation:{}'.format(user_id)
            for c_id, unread in user_cs.items():
                unread_cache.hset(new_key, c_id, int(unread))

            # 删除原有的记录
            unread_cache.delete(user_key)
        old_records = unread_cache.keys(u'user:*:conversation')
        for old_key in old_records:
            unread_cache.delete(old_key[7:])
