# -*- coding: UTF-8 -*-
import os
import re

from django.conf import settings
from gm_upload.utils.qiniu_tool import QiniuTool
from .logger import log_error


class ChannelPackage(object):
    # 渠道识别前缀
    channel_prefix = 'gmchannel'

    def __init__(self, api_data, version):
        self.apk_data = api_data
        self.version = version
        self.apk = None

    def build_channel_apk(self, channel_name):
        cp = re.compile(r'[^{}]+')
        self.apk = self.channel_prefix + '.apk'
        walle_cli_path = os.getcwd() + '/walle-cli-all.jar'
        with open(self.apk, 'wb') as fw:
            fw.write(self.apk_data)
        os.system('java -jar {0} batch -c {1} {2}'.format(walle_cli_path, channel_name, self.apk))
        with open(self.channel_prefix + '_' + channel_name + '.apk', 'rb') as fr:
            data = fr.read()
        targe_apk = self.channel_prefix + '_' + channel_name + '.apk'
        cmd_res = os.popen('java -jar walle-cli-all.jar show %s' % targe_apk)
        ret_res = cmd_res.readlines()[0]
        target_channel_info = cp.findall(ret_res)[1]
        if target_channel_info and channel_name == target_channel_info.split('=')[1]:
            return data
        else:
            log_error()
        os.remove(self.apk)
        os.remove(self.channel_prefix + '_' + channel_name + '.apk')

    def upload_apk(self, channel_name):
        chn_apk_data = self.build_channel_apk(channel_name)
        apk_uri = self.apk_key(channel_name, self.version)
        QiniuTool.delete(apk_uri, settings.APK_SCOPE)
        ret = QiniuTool.upload(chn_apk_data, apk_uri, settings.APK_SCOPE)
        return ret

    @classmethod
    def apk_key(cls, channel, version):
        build_dir = getattr(settings, 'APK_BUILD_DIR', '')
        if channel:
            uri = '{version}/{channel}/gengmei_{channel}.apk'.format(version=version, channel=channel)
        else:
            uri = '{version}/gengmei.apk'.format(version=version)
        if build_dir:
            uri = '{build_dir}/{uri}'.format(build_dir=build_dir, uri=uri)
        return uri

    @classmethod
    def apk_url(cls, channel, version):
        key = cls.apk_key(channel, version)
        url = settings.APK_DOMAIN + key
        return url

    @classmethod
    def publish_apk(cls, channel, version, need_refresh=True):
        apk_scope = settings.APK_SCOPE
        version_key = cls.apk_key(channel, version)
        current_key = cls.apk_key(channel, settings.APK_RELEASE_DIR)
        ret, info = QiniuTool.bucket.stat(apk_scope, current_key)
        if ret:
            QiniuTool.delete(current_key, apk_scope)
        QiniuTool.copy(version_key, current_key, apk_scope, apk_scope)
        if need_refresh:
            QiniuTool.refresh(['http://qiniu.dl.igengmei.com/' + current_key])
        return True
