from pathlib import Path
import xml.etree.ElementTree as ET

BASE = Path('/home/sebas/work/tasks/T-ballbox-rebrand-v3/decode')

def load_strings(path):
    root = ET.parse(path).getroot()
    data = {}
    for el in root.findall('string'):
        name = el.attrib.get('name')
        if name:
            data[name] = el.text or ''
    return data

SPANISH_SRC = load_strings(BASE/'tcn-v3/res/values-es/strings.xml')
OVERRIDES = {
    'background_info_item_language_by_paging': 'Idioma',
    'app_ui_switch_language': 'Español',
    'setting_language_english': 'Español',
    'english': 'Español',
    'chinese': 'Español',
    'languags_type_en': 'Español',
    'languags_type_zh': 'Español',
    'background_menu_language': 'Español',
    'background_wmlanguagek': 'Español',
    'background_wmlanguagev': 'Español',
    'background_wmlanguagey': 'Español',
}

TARGETS = [
    BASE/'skin/res/values/strings.xml',
    BASE/'tcn-v3/res/values/strings.xml',
    BASE/'tcn-v3/res/values-en/strings.xml',
    BASE/'tcn-v3/res/values-zh-rCN/strings.xml',
    BASE/'tcn-v3/res/values-zh-rTW/strings.xml',
]

for path in TARGETS:
    if not path.exists():
        continue
    tree = ET.parse(path)
    root = tree.getroot()
    changed = 0
    for el in root.findall('string'):
        name = el.attrib.get('name')
        if not name:
            continue
        if name in SPANISH_SRC:
            new = SPANISH_SRC[name]
            if el.text != new:
                el.text = new
                changed += 1
        if name in OVERRIDES:
            new = OVERRIDES[name]
            if el.text != new:
                el.text = new
                changed += 1
    tree.write(path, encoding='utf-8', xml_declaration=True)
    print(path, changed)

ARRAY_TARGETS = [
    BASE/'tcn-v3/res/values/arrays.xml',
    BASE/'tcn-v3/res/values-en/arrays.xml',
]
for path in ARRAY_TARGETS:
    if not path.exists():
        continue
    tree = ET.parse(path)
    root = tree.getroot()
    changed = 0
    for el in root.findall('.//item'):
        txt = el.text or ''
        if '101~Language 0~10(0,R/W) 0:Chinese 1:English' in txt:
            el.text = txt.replace('101~Language 0~10(0,R/W) 0:Chinese 1:English','101~Idioma 0~10(0,R/W) 0:Español 1:Español')
            changed += 1
    tree.write(path, encoding='utf-8', xml_declaration=True)
    print(path, changed)
