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

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

def sdkLebianChange(game, sdk, config):
    '''
    乐变的处理，理论上只需要有接入的游戏需要处理
    考虑到技术人员不可控，所以每个游戏都处理
    '''
    print('change Provider Authorities')

    subChannel = config['subChannel']

    decompliePath = file_utils.getDecompliePath(game, sdk, subChannel, config['cache'])
    manifest = os.path.join(decompliePath, 'AndroidManifest.xml')
    changeProviderAuthorities(manifest, config['packageName'])
    return 0

def changeProviderAuthorities(manifest, packageName):
    '''
    标识为com.excelliance
    更改provider的android:authorities
    更改activity的android:taskAffinity
    '''
    for key in namespaces:
        ET.register_namespace(key, namespaces[key])

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

    packageTag = 'com.excelliance'
    attrAuthorities = xml_utils.getNamespacesFormat('android:authorities', namespaces)
    for provider in root.findall('application/provider'):
        
        if attrAuthorities not in provider.attrib:
            continue

        authorities = provider.attrib[attrAuthorities]
        if packageTag not in authorities:
            continue

        auth = packageName + authorities[authorities.index(':'):]
        provider.attrib[attrAuthorities] = auth
    
    attrName = xml_utils.getNamespacesFormat('android:name', namespaces)
    attrTaskAffinity = xml_utils.getNamespacesFormat('android:taskAffinity', namespaces)

    for activity in root.findall('application/activity'):
        if packageTag not in activity.attrib[attrName]:
            continue

        if attrTaskAffinity in activity.attrib:
            activity.attrib[attrTaskAffinity] = packageName

    tree.write(manifest, encoding)