import file_utils
import package_utils_record
import os.path
import sys
import json
import importlib
from PIL import Image, ImageDraw

def packageWeb():
    if len(sys.argv) < 2:
        print('argument is missing')
        return 1

    # 打包配置的路径
    packageConfig = sys.argv[1]

    jsonText = file_utils.readFile(packageConfig)
    config = json.loads(jsonText)

    print('*************config*****************')
    print(jsonText)
    print('************************************')

    package(config, config['sdk'])

def package(config, sdk):
    print('use script 3rd')
    jsonConfig = {}
    game = config['app']
    subChannel = None

    if 'subChannel' in config:
        subChannel = config['subChannel']
        jsonConfig['subChannel'] = config['subChannel']

    # 必须参数
    jsonConfig['packageName'] = config['packageName']
    jsonConfig['name'] = config['name']

    # 可选参数
    if 'outName' in config:
        jsonConfig['outName'] = config['outName']

    if 'outPath' in config:
        jsonConfig['outPath'] = config['outPath']

    if 'changeIcon' in config:
        jsonConfig['changeIcon'] = toBoolean(config['changeIcon'])

    if 'addLauncher' in config:
        jsonConfig['addLauncher'] = toBoolean(config['addLauncher'])

    if 'versionCode' in config:
        jsonConfig['versionCode'] = config['versionCode']

    if 'versionName' in config:
        jsonConfig['versionName'] = config['versionName']

    if 'targetSdkVersion' in config:
        jsonConfig['targetSdkVersion'] = config['targetSdkVersion']
        
    if 'v2disable' in config:
        jsonConfig['v2disable'] = toBoolean(config['v2disable'])

    if 'aapt2disable' in config:
        jsonConfig['aapt2disable'] = toBoolean(config['aapt2disable'])

    # sdk相关参数
    if 'properties' in config:
        jsonConfig['properties'] = config['properties']

    jsonConfig['bgMusic'] = config['bgMusic']
    if 'recordConfig' in config:
        recordConfig = config['recordConfig']
        setRecordConfig(jsonConfig, recordConfig)

        userIcon = recordConfig['userIcon']
        suffix = userIcon[userIcon.index('.'):]
        item = {'fromFile':userIcon, 'toFile':'res/drawable/float_sdk_user_icon' + suffix}

        if 'copyList' in config:
            copyList = config['copyList']
            copyList.append(item)
        else:
            config['copyList'] = [item]

    configData = jsonConfig['configData']
    properties = jsonConfig['properties']
    configData['agent'] = properties['agent']
    configData['buildTime'] = properties['version']
    configData['appId'] = properties['appid']
    configData['appkey'] = properties['appkey']
    if 'host' in properties:
        configData['host'] = properties['host']

    if 'deleteList' in config:
        jsonConfig['deleteList'] = config['deleteList']

    

    # 获取sdk相关配置
    getSdkConfig(sdk, jsonConfig, config)

    # 生成配置文件
    createOrUpdateConfigFile(game, sdk, jsonConfig)

    # 拷贝资源
    copyRes(game, sdk, subChannel, config)

    # 打包
    package_utils_record.packConsole(game, sdk, subChannel)

def setRecordConfig(config, recordConfig):
    configData = None
    if 'configData' in config:
        configData = config['configData']
        configData['bgMusic'] = 'bg_music.mp3'
        configData['gameId'] = recordConfig['gameId']
        configData['gameName'] = recordConfig['gameName']
        configData['gameIcon'] = recordConfig['gameIcon']
        configData['gameUrl'] = recordConfig['gameUrl']
        configData['skinId'] = recordConfig['skinId']
        configData['host'] = recordConfig['host']
        configData['appDownUrl'] = recordConfig['appDownUrl']
        configData['userId'] = recordConfig['userId']
        configData['userName'] = recordConfig['userName']
        configData['userDesc'] = recordConfig['userDesc']
    else:
        config['configData'] = {
            'bgMusic':'bg_music.mp3',
            'gameId':recordConfig['gameId'],
            'gameName':recordConfig['gameName'],
            'gameIcon':recordConfig['gameIcon'],
            'gameUrl':recordConfig['gameUrl'],
            'skinId':recordConfig['skinId'],
            'host':recordConfig['host'],
            'appDownUrl':recordConfig['appDownUrl'],
            'userId':recordConfig['userId'],
            'userName':recordConfig['userName'],
            'userDesc':recordConfig['userDesc']
        }

def toBoolean(booleanStr):
    if type(booleanStr) == bool:
        return booleanStr

    if booleanStr == 'true':
        return True
    return False

def getSdkConfig(sdk, jsonConfig, config):
    scriptPath = os.path.join(file_utils.getCurrentPath(), 'sdk_script')
    sdkScript = getScriptMapping(sdk)
    targetScript = os.path.join(scriptPath, '%s.py' % sdkScript)
    if not os.path.exists(targetScript):
        print('%s no exists' % targetScript)
        return 0

    sys.path.append(scriptPath)
    module = importlib.import_module(sdkScript)# 动态导入相应模块
    module.getSdkConfig(jsonConfig, config)# 执行脚本功能
    sys.path.remove(scriptPath)

def createOrUpdateConfigFile(game, sdk, jsonConfig):
    '''
    更新配置文件
    '''
    if 'subChannel' not in jsonConfig:
        return 0

    print('createOrUpdateConfigFile ...')

    channelPath = file_utils.getChannelPath(game, sdk)
    configPath = os.path.join(channelPath, 'config.json')
    #configPath = os.path.join(file_utils.getCurrentPath(), 'test', 'test.json')

    if os.path.exists(configPath):
        # 更新数据
        jsonText = file_utils.readFile(configPath)
        config = json.loads(jsonText)

        count = 0
        if type(config) == list:
            for item in config:
                if item['subChannel'] == jsonConfig['subChannel']:
                    print('find same config ...')
                    del config[count]
                    break

                count += 1

            config.append(jsonConfig)

            createConfigFile(config, configPath)
        elif type(config) == dict:
            if config['subChannel'] == jsonConfig['subChannel']:
                print('find same config ...')
                createConfigFile(jsonConfig, configPath)
            else:
                print('add a new config ...')
                config = [config, jsonConfig]

                createConfigFile(config, configPath)
    else:
        print('create a new config ...')
        createConfigFile([jsonConfig], configPath)

def createConfigFile(jsonConfig, configPath):
    '''
    创建配置文件
    '''
    jsonStr = json.dumps(jsonConfig, ensure_ascii=False)
    print('*************out config*************')
    print(jsonStr)
    print('************************************')
    file_utils.createFile(configPath, jsonStr)

def copyRes(game, sdk, subChannel, config):
    '''
    拷贝资源
    '''
    if subChannel is None:
        return 0

    channelPath = file_utils.getChannelPath(game, sdk)
    subChannelPath = os.path.join(channelPath, subChannel)
    if 'icon' in config and os.path.exists(config['icon']):
        mipmapSupport = ['mipmap-xhdpi', 'mipmap-xxhdpi', 'mipmap-xxxhdpi']
        for mipmap in mipmapSupport:
            mipmapPath = os.path.join(subChannelPath, 'icon', mipmap)
            if not os.path.exists(mipmapPath):
                os.makedirs(mipmapPath)
            iconPath = os.path.join(subChannelPath, 'icon', mipmap, 'record_sdk_icon.png')
            if not os.path.exists(iconPath):
                file_utils.createFile(iconPath, '')
            if mipmap == 'mipmap-xhdpi':
                size = 96
            elif mipmap == 'mipmap-xxhdpi':
                size = 144
            else:
                size = 192
            roundRectangleIcon(config['icon'], iconPath, size)
            #file_utils.copyFile(config['icon'], iconPath)

    if 'splash' in config and os.path.exists(config['splash']):
        splashPath = os.path.join(subChannelPath, 'splash', 'drawable-hdpi', 'shanshen_sdk_launcher_bg.jpg')
        file_utils.copyFile(config['splash'], splashPath)

    if 'bgMusic' in config and os.path.exists(config['bgMusic']):
        musicPath = os.path.join(subChannelPath, 'assets', 'bg_music.mp3')
        file_utils.copyFile(config['bgMusic'], musicPath)

    if 'copyList' in config:
        for item in config['copyList']:
            if item['toFile'] == '':
                continue

            if not os.path.exists(item['fromFile']):
                continue

            toFile = item['toFile']
            if toFile[:3] == 'res':
                toFile = 'image' + toFile[3:]
                
            resPath = getPackagePath(subChannelPath, toFile)
            file_utils.copyFile(item['fromFile'], resPath)

    if 'package' in config and os.path.exists(config['package']):
        newGameApk = config['package']
        gameApk = file_utils.getFullGameApk(game)
        file_utils.copyFile(newGameApk, gameApk)

    if 'languageList' in config:
        for item in config['languageList']:
            languagePath = os.path.join(subChannelPath, 'merge', item['apkLanguage'])
            file_utils.copyFile(item['language'], languagePath)

def roundRectangleIcon(iconPath, outPath, outSize):
    markerPath = os.path.join(file_utils.getFullInternalPath(), 'marker', 'marker.png')
    img = Image.open(iconPath).resize((192, 192)).convert("RGBA")
    marker = Image.open(markerPath).resize((192, 192)).convert("RGBA")
    img.paste(marker, (0, 0), marker)

    rad = 30  # 设置半径 
    circle = Image.new('L', (rad * 2, rad * 2), 0)
    draw = ImageDraw.Draw(circle)
    draw.ellipse((0, 0, rad * 2, rad * 2), fill=255)
    alpha = Image.new('L', img.size, 255)
    w, h = img.size
    alpha.paste(circle.crop((0, 0, rad, rad)), (0, 0))
    alpha.paste(circle.crop((0, rad, rad, rad * 2)), (0, h - rad))
    alpha.paste(circle.crop((rad, 0, rad * 2, rad)), (w - rad, 0))
    alpha.paste(circle.crop((rad, rad, rad * 2, rad * 2)), (w - rad, h - rad))
    img.putalpha(alpha)

    img.resize((outSize, outSize)).save(outPath, 'png')

def getPackagePath(basePath, packageName):
    '''
    包名对应的目录
    '''
    packageNameSplit = packageName.replace('\\', '/').split('/')
    newPath = basePath
    for item in packageNameSplit:
        newPath = os.path.join(newPath, item)
    return newPath

def getMappingSdk(config):
    return config['sdk']

def getScriptMapping(sdk):
    return sdk

#packageWeb()