#! /usr/bin/python3

from xml.dom import minidom
import sys

def msgIsForFile(msg, f):
    locations=msg.getElementsByTagName("location")
    if locations and locations[0].getAttribute("filename")==f:
        return True
    return False


def traduit(f, msg):
    """
    ouvre le fichier f, ouvre un fichier f+".tmp"
    trouve les messages qui vont bien et propose de faire les remplacements
    """
    with open(f, "r") as infile:
        text=infile.read()
        copie=""+text
        localMsg=[m for m in msg if msgIsForFile(m,f)]
        for m in localMsg:
            sources=m.getElementsByTagName("source")
            translations=m.getElementsByTagName("translation")
            if sources and translations and translations[0].firstChild:
                s=sources[0].firstChild.nodeValue
                s.replace("&apos;","'")
                s.replace("&amp;","&")
                t=translations[0].firstChild.nodeValue
                print(s, "=>", t)
                if translations[0].getAttribute("type")=="obsolete": continue
                copie=copie.replace(s, t)
    with open(f+".tmp","w") as outfile:
        outfile.write(copie)
    return

if __name__=="__main__":
    tsFileName=sys.argv[1]
    doc=minidom.parse(tsFileName)
    msg=doc.getElementsByTagName("message")
    locations=doc.getElementsByTagName("location")
    filenames=sorted(list(set([l.getAttribute("filename") for l in locations])))
    for f in filenames:
        traduit(f, msg)
        
