import file_utils
import os.path

def execute(game, sdk, config):
    if not checkConfig(config):
        return 1

    subChannel = config['subChannel']

    createJmhyProperties(game, sdk, subChannel, config)
    
    return copyWechatCode(game, sdk, subChannel, config)

def checkConfig(config):
    '''
    检查配置
    '''
    if 'properties' not in config:
        print('properties not exists in config')
        return False

    properties = config['properties']
    
    if 'agent' not in properties or 'version' not in properties:
        print('agent or version not exists in properties')
        return False

    '''if 'appid' not in config or 'appkey' not in config:
        print('appid or appkey not exists in config')
        return False'''

    return True

def createJmhyProperties(game, sdk, subChannel, config):
    '''
    创建jmhy.properties
    '''
    print('create jmhy.properties')
    propValue = config['properties']
    decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
    properties = os.path.join(decompliePath, 'assets', 'jmhy.properties')
    content = ''
    for key in propValue:
        content = '%s%s=%s\n' % (content, key, propValue[key])
        print('write properties : %s = %s' % (key, propValue[key]))
    file_utils.createFile(properties, content)
    return 0

def copyWechatCode(game, sdk, subChannel, config):
    '''
    拷贝微信sdk的代码
    '''
    print('copy WXPayEntryActivity.smali')
    sdkPath = file_utils.getFullSDKPath(sdk)

    WXPayEntryActivity = 'WXPayEntryActivity.smali'

    wxFile = os.path.join(sdkPath, 'smali', WXPayEntryActivity)
    decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
    smaliPath = os.path.join(decompliePath, 'smali')
    targetPath = file_utils.getPackagePath(smaliPath, config['packageName'])
    targetFile = os.path.join(targetPath, 'wxapi', WXPayEntryActivity)
    ret = file_utils.copyFile(wxFile, targetFile)
    if ret:
        return ret

    file_utils.replaceContent(targetFile, '${packageName}', config['packageName'].replace('.', '/'))

    return 0