import file_utils
import common_utils
import xml_utils
import os.path
import xml.etree.ElementTree as ET
import json


namespaces = {'android': 'http://schemas.android.com/apk/res/android'}
encoding = 'UTF-8'


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

    subChannel = config['subChannel']

    createJmhyProperties(game, sdk, subChannel, config)
    addLauncher(game, sdk, subChannel, config)
    common_utils.changeApplication(game, sdk, subChannel, config, 'com.tygrm.sdk.TYRApplication')

    #生成json
    addAKJson(game, sdk, subChannel, config)
    addPJson(game, sdk, subChannel, config)

    return 0


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])
    file_utils.createFile(properties, content)
    return 0


def addLauncher(game, sdk, subChannel, config):
    '''
    添加启动图
    '''
    decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])

    # 修改主文件信息
    print('change launcher config...')
    manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
    activity = xml_utils.getLauncherActivityName(manifest)
    if activity == 'com.inner.sdk.ui.LauncherActivity':
        print('add launcher already exist...')
        return 1

    orientation = xml_utils.getScreenOrientation(manifest)
    activity = xml_utils.removeLauncherActivity(manifest)
    addLauncherActivity(manifest, orientation)

    # 修改跳转的
    launcherActivity = os.path.join(decompliePath, 'smali', 'com', 'inner', 'sdk', 'ui', 'LauncherActivity.smali')
    file_utils.replaceContent(launcherActivity, '{class}', activity)

    print('change launcher %s to %s' % (activity, 'com.inner.sdk.ui.LauncherActivity'))

    # config['oldLauncher'] = activity

    return 0


def addLauncherActivity(manifest, screenOrientation):
    '''
    添加启动的activity
    '''
    for key in namespaces:
        ET.register_namespace(key, namespaces[key])

    tree = ET.parse(manifest)
    root = tree.getroot()

    # activity
    activity = ET.Element('activity', {'android:name': 'com.inner.sdk.ui.LauncherActivity',
                                       'android:configChanges': 'orientation|screenSize|keyboardHidden',
                                       'android:screenOrientation': screenOrientation})
    intent = ET.Element('intent-filter')
    action = ET.Element('action', {'android:name': 'android.intent.action.MAIN'})
    category = ET.Element('category', {'android:name': 'android.intent.category.LAUNCHER'})
    intent.append(action)
    intent.append(category)
    activity.append(intent)

    application = root.find('application')
    application.insert(0, activity)

    tree.write(manifest, encoding)


def deleteSplash(game, sdk, subChannel, config):
    '''
    删除闪屏
    '''
    if game != 'wzjh':
        return 0
    channelPath = file_utils.getSubChannelPath(game, sdk, subChannel)
    print('delete Splash...')
    decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
    manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
    activity = xml_utils.getLauncherActivityName(manifest)
    activity = xml_utils.removeLauncherActivity(manifest)
    xml_utils.deleteActivityByName(manifest, 'com.hugenstar.nanobox.NaNoUnityContext')
    addGameLauncherActivity(manifest, config['screenOrientation'], 'com.hugenstar.nanobox.NaNoUnityContext')
    return 0


def addGameLauncherActivity(manifest, screenOrientation, activity):
    '''
    修改特定游戏启动的activity
    '''
    for key in namespaces:
        ET.register_namespace(key, namespaces[key])

    tree = ET.parse(manifest)
    root = tree.getroot()

    # activity
    '''<activity android:name=".LauncherActivity"
            android:theme="@style/LauncherStyle">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>'''

    activity = ET.Element('activity', {'android:name': activity,
                                       'android:theme': '@android:style/Theme.Holo.Light.NoActionBar.Fullscreen',
                                       'android:launchMode': 'singleTop',
                                       'android:configChanges': 'orientation|screenSize|keyboardHidden',
                                       'android:screenOrientation': screenOrientation})
    intent = ET.Element('intent-filter')
    action = ET.Element('action', {'android:name': 'android.intent.action.MAIN'})
    category = ET.Element('category', {'android:name': 'android.intent.category.LAUNCHER'})
    intent.append(action)
    intent.append(category)
    activity.append(intent)
    intent2 = ET.Element('intent-filter')
    category = ET.Element('category', {'android:name': 'android.intent.category.LEANBACK_LAUNCHER'})
    intent2.append(category)
    activity.append(intent2)

    application = root.find('application')
    application.insert(0, activity)

    tree.write(manifest, encoding)

def addAKJson(game, sdk, subChannel, config):
        '''
        添加config.json
        '''
        if 'tianyuyou' not in config:
            return 0

        print('add config.json...')
        decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
        configJson = os.path.join(decompliePath, 'assets', 'tygrm_ak.json')
        jsonText = json.dumps(config['configData'], ensure_ascii=False)
        file_utils.createFile(configJson, jsonText)
        return 0


def addPJson(game, sdk, subChannel, config):
    '''
    添加config.json
    '''
    if 'configData' not in config:
        return 0

    print('add config.json...')
    decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
    configJson = os.path.join(decompliePath, 'assets', 'tygrm_config_p.json')
    jsonText = json.dumps(config['configData'], ensure_ascii=False)
    file_utils.createFile(configJson, jsonText)
    return 0