import os
from celery import shared_task
from django.conf import settings
import requests

from gm_upload.utils.qiniu_tool import QiniuTool

from middleware.rpc import rpc_invoker
from utils.channel_package_tools import ChannelPackage, QiniuFileTool
from utils.logger import log_error, info_logger


@shared_task
def version_release_task(packed_channels, version_id=None, version=None):  # 一键发布，发布完成邮件通知
    rpc = rpc_invoker
    version = version
    channel_ids = list()
    for version2channel in packed_channels:
        channel = version2channel['url_name']
        channel_ids.append(version2channel.get('id'))
        try:
            ChannelPackage.publish_apk(channel, version)
        except:
            log_error()
            raise Exception('发布失败')
    # 发布
    rpc['venus/sun/channel_build/version/release'](
        version_id=version_id, channel_ids=channel_ids
    ).unwrap()
    #  email notify
    # rpc.origin['endpoint'](version=version, channels=channels).unwrap()


@shared_task
def channel_build_one(version=None, channel=None, data=None):
    url = ChannelPackage.apk_url('', version)
    for _ in range(5):
        try:
            r = requests.get(url, stream=True)
            info_logger.debug(url)
            if r.content:
                break
        except:
            info_logger.debug('第%s下载失败%s：', _, url)
    chn_pkg = ChannelPackage(r.content, version)
    build_one_channel(chn_pkg, channel)


@shared_task
def channel_build(version=None, channels=None, data=None, ):
    url = ChannelPackage.apk_key('', version)
    QiniuTool.delete(url, settings.APK_SCOPE)
    target_path = ChannelPackage.get_parent_path(data)
    QiniuFileTool.upload_file(target_path, url, settings.APK_SCOPE)  # 上传母包
    if not channels:
        # channels = [settings.DEFAULT_CHANNEL]
        return

    info_logger.debug(channels)
    chn_pkg = ChannelPackage(data, version)
    # 遍历渠道号并创建对应渠道号的apk文件
    for channel in channels:
        build_one_channel(chn_pkg, channel)


def build_one_channel(pkg_obj, channel):
    info_logger.debug(channel)
    if not channel:
        return
    channel = channel.strip()
    ret = pkg_obj.upload_apk(channel)
    info_logger.debug(ret)
    if 'file' in ret:
        # 打包
        rpc_invoker['venus/sun/channel_build/channel/pack'](
            version=pkg_obj.version, url_name=channel
        ).unwrap()
