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

from django.conf import settings
from pywe_marketcode import applycodedownload
from pywe_storage import RedisStorage

from marketcode.models import MarketCodeInfo
from utils.redis.connect import r


WECHAT = settings.WECHAT


def marketcodedownload(application_id, code_start, code_end, isv_application_id='', iv=''):
    wxcfg = WECHAT.get('JSAPI', {})

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

    codes = applycodedownload(application_id=application_id, code_start=code_start, code_end=code_end, appid=appid, secret=secret, token=None, storage=RedisStorage(r), iv=iv)

    lattice, code, code_index, code_url = '', '', '', ''
    for idx, item in enumerate(codes.split()):
        if idx % 4 == 0:
            lattice = item
        if idx % 4 == 1:
            code = item
        if idx % 4 == 2:
            code_index = item
        if idx % 4 == 3:
            code_url = item
            MarketCodeInfo.objects.create(
                isv_application_id=isv_application_id,
                application_id=application_id,
                lattice=lattice,
                code=code,
                code_index=code_index,
                code_url=code_url
            )


