# -*- coding: UTF-8 -*-


def queryset_dec(qs, need_instant_data=False):
    """解构queryset, 使其可以被序列化或缓存
       need_install_data 是否需要立即保存当前数据状态
       添加该条件主要是在延迟过程中避免数据状态发生变化，而导致页面看到的数据和导出的数据不一致
    """
    if need_instant_data:
        qs._hints.update({'_install_data': list(qs.values_list('id', flat=True))})
    qs_dict = {'model': qs.model, 'query': qs.query, '_db': qs._db, '_hints': qs._hints}
    return qs_dict


def queryset_enc(qs_dict):
    """重新构建queryset
    """
    m = qs_dict['model']
    qs = m.objects.all()
    qs.query = qs_dict['query']
    qs._db = qs_dict.get('_db', None)
    qs._hints = qs_dict.get('_hints', {})
    return qs


def big_qs_iter(qs, fetch_num=1000, trace=False):
    cnt = qs.count()
    bgn = 0
    step = fetch_num
    while bgn <= cnt:
        if trace:
            print u'%s/%s' % (bgn, cnt)
        for obj in qs[bgn: bgn+step]:
            yield obj
        bgn += step


def big_qs_loop(qs, fetch_num=1000, trace=False):
    bgn = 0
    step = fetch_num
    while True:
        if trace:
            print u'%s' % (qs.count())
        objs = qs[bgn: step]
        if not objs:
            break
        for obj in objs:
            yield obj


def big_id_iter(qs, fetch_num=1000, trace=False):
    ids = qs._hints.get('_install_data', [])
    bgn = 0
    step = fetch_num
    while bgn <= len(ids):
        if trace:
            print u'%s/%s' % (bgn, len(ids))
        for id in ids[bgn: bgn+step]:
            yield id
        bgn += step