#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

import sys
import json
from pathlib import Path
import lxml.etree
import lxml

def print_usage():
    print('Usage:')
    print(f'  {sys.argv[0]} <android_res_folder> <default_language> <arb_files_output_folder>')

def convert_xml_to_arb(androidResFolder, defaultLanguage, arbOutputFolder):
    xmls_path = {
        defaultLanguage.lower(): androidResFolder.joinpath('values/strings.xml'),
        **{
            path.parent.name.split('-')[-1].lower(): path
            for path in androidResFolder.glob('values-*/strings.xml')
        }
    }
    untranslatables = dict()
    translations = {lang: dict() for lang in xmls_path}
    for lang, xml_path in xmls_path.items():
        etree = lxml.etree.fromstring(xml_path.read_bytes())
        for translated_string in etree.findall('string'):
            if translated_string.attrib.get('translatable', 'true').lower() == 'false':
                untranslatables[translated_string.attrib['name']] = translated_string.text
            else:
                translations[lang][translated_string.attrib['name']] = translated_string.text
    for d in translations.values():
        d.update(untranslatables)
    for k, v in translations.items():
        arbOutputFolder.joinpath(f'strings_{k}.arb').write_text(json.dumps(v, indent=4, sort_keys=True, ensure_ascii=False))

def main():
    if len(sys.argv) != 4:
        print_usage()
    else:
        convert_xml_to_arb(Path(sys.argv[1]), sys.argv[2], Path(sys.argv[3]))


if __name__ == '__main__':
    main()
